Page Content:
1.State-Introduction
2.State-Class Component
3.State-Function Component
1.Introduction:
1.React uses the state to maintain data & information about any component.
2.The change in state over time can happen as a response to user action or system event.
3.a component with a state is called a stateful component.
4.states are important to make components interactive & dynamic.
5.a state represents the component’s local state or information.
6.State can only be accessed or modified inside the component or by the component directly.
2.State for Class Component:
Below code shows how to create stateful class component usinf ES6 syntax.
App.jsx
import React from 'react';
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
data: "Welcome to webdev99"
};
}
render() {
return (
<div>
<h1>{this.state.data}</h1>
</div>
);
}
}
export default App;
main.jsx
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App.jsx';
ReactDOM.render(<App />, document.getElementById('app'));

Now, let’s change the state based on button click for the class component:
To change the state we use this.setstate method which can be called inside changeState method, & to bind this changeState method to our class component we can use bind method as below,
this.changeState=this.changeState.bind(this);
App.jsx
import React from 'react';
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
data: "Welcome to webdev99"
};
this.changeState=this.changeState.bind(this);
}
changeState(){
this.setState({data: "data updated"});
}
render() {
return (
<div>
<h1>{this.state.data}</h1>
<input
type="button"
value="update data"
onClick={this.changeState}
/>
</div>
);
}
}
export default App;

After button click state changes to “data updated”,

3.state for Functional component:
Actually, functional components were stateless components before React v16. 8.0.
(i.e we couldn’t use state in functional component)
but after React v16. 8.0. now we can use state in functional components using the concept of hooks.
React provides a build-in hook called useState() which can be used to maintain state as below.
myComponent.jsx
import React, { useState } from 'react';
function myComponent() {
// Declare a new state variable, which we'll call "count"
const [count, setCount] = useState(0);
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>
Click me
</button>
</div>
);
}
export default myComponent;
