Managing State
State is a component’s memory. It allows components to remember information and respond to user interactions by re-rendering with updated data.When to Use State
Use state when a component needs to “remember” something that changes over time:- ✅ Form input values
- ✅ Whether a modal is open or closed
- ✅ The currently selected tab
- ✅ Data fetched from an API
- ✅ Items in a shopping cart
Not everything needs to be state! If you can calculate something from props or existing state, don’t make it a separate state variable.
Using useState
TheuseState Hook lets you add state to functional components:
useState Basics
State Updates
Calling a setter function tells React to re-render the component with the new value:State updates are asynchronous! React batches multiple state updates for performance. Don’t rely on the state value immediately after calling the setter.
Functional Updates
When the new state depends on the previous state, use a function:State Immutability
Never modify state directly. Always create new values:Updating Objects
Updating Arrays
Updating Nested Objects
Multiple State Variables
You can useuseState multiple times in a component:
When to Group State
Lifting State Up
When multiple components need to share state, move it to their common parent:Complete Shopping Cart Example
Best Practices
Key principles:
- Keep state minimal - derive values when possible
- Don’t duplicate data between state and props
- Avoid deeply nested state structures
- Group related state together
- Lift state up when components need to share it