State in React
⏱ Estimated reading time: 2 min
State is used to store and manage data that changes over time in a React component. When state changes, React automatically re-renders the component to reflect the updated data.
What is State?
-
State is local to a component
-
It can change based on user interaction or logic
-
Updating state causes the UI to update
Using State with useState
In functional components, state is managed using the useState hook.
-
count→ current state value -
setCount→ function to update state -
0→ initial state value
Updating State
Correct Way
Using Previous State
This is recommended when the new state depends on the old state.
State with Multiple Values
Update part of the state:
State vs Props
| State | Props |
|---|---|
| Managed inside component | Passed from parent |
| Can change | Read-only |
| Triggers re-render | Does not change itself |
Common Use Cases for State
-
Form inputs
-
Toggle buttons
-
Counters
-
Modal visibility
-
API data storage
Important Rules of State
-
❌ Do not modify state directly
-
✅ Always use the setter function
-
State updates may be asynchronous
Example: Toggle State
Key Points
-
State holds dynamic data
-
useStateis the most common hook -
Updating state re-renders the component
-
Use previous state when needed
Register Now
Share this Post
← Back to Tutorials