State in React JS
State in a React component is an object that holds key-value pairs representing different pieces of data that the component needs to manage. When the state of a component changes, React automatically re-renders the component to reflect the new state.
To manage state in a class component, you can use the this.state
property to access the state object and the this.setState()
method to update the state. In functional components, you can use the useState
hook to create and manage state.
Here's an example of state usage in a class component:
class Counter extends React.Component {
constructor(props) {
super(props);
this.state = { count: 0 };
}
increment() {
this.setState(prevState => ({ count: prevState.count + 1 }));
}
render() {
return (
<div>
<p>Count: {this.state.count}</p>
<button onClick={() => this.increment()}>Increment</button>
</div>
);
}
}
And here's an example using the useState
hook in a functional component:
import React, { useState } from 'react';
const Counter = () => {
const [count, setCount] = useState(0);
const increment = () => {
setCount(prevCount => prevCount + 1);
};
return (
<div>
<p>Count: {count}</p>
<button onClick={increment}>Increment</button>
</div>
);
};
In both examples, the Counter
component has an internal state with a count
property, and it re-renders whenever the state changes (i.e., when the button is clicked and the count increases).