In a React application, state refers to a built-in object used to store property values that belong to a component. When the state object changes, the component re-renders to reflect the new values.
Why State Is Important
State lets your components keep track of information between renders—like user input, API data, toggles, etc.
How to Use State in React
1. Using useState in Function Components
import React, { useState } from 'react';
function Counter() {
const [count, setCount] = useState(0);
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>Click me</button>
</div>
);
}
useState(0)initializes the state.countis the current state value.setCountis the function to update the state.
2. State in Class Components (older style)
class Counter extends React.Component {
constructor(props) {
super(props);
this.state = { count: 0 };
}
render() {
return (
<div>
<p>You clicked {this.state.count} times</p>
<button onClick={() => this.setState({ count: this.state.count + 1 })}>
Click me
</button>
</div>
);
}
}
Re-rendering
When you update the state using setState (class) or setSomething (hook), React will re-render that component and its children if necessary.
Things to Remember
- State updates are asynchronous.
- Don’t modify state directly; always use the update functions.
- You can have multiple
useStatehooks in one component.
