React State Management
State Management
What is "State" in React?
State is a built-in object that allows components to create and manage their own data. When state changes, the component re-renders to reflect the new data in the UI.
Why Do We Need State Management?
- Lifting state up becomes hard as apps grow.
- Components need to share state.
- Some data needs to be global (e.g., user authentication, theme).
Levels of State Management
-
Local State (within a component)
- Managed using useState or useReducer
- Best for UI interactions (modals, toggles, form inputs)
-
Shared State (between components)
- Lift state up to a common ancestor and pass it down via props
- Can use Context API if deeply nested
-
Global State (accessible from anywhere)
- Useful for app-wide data like user info, cart, theme
- Tools: React Context API, Redux, Zustand, Jotai, Recoil
-
Server State
- Data from external APIs that needs caching, syncing, etc.
- Tools: React Query, SWR
Popular State Management Tools
Tool - Redux
Best for - Large-scale, predictable State
Example
useState(0)
initializescount
with value0
.setCount
updates the state.- When a user clicks "+" or "–", the count updates and the UI re-renders automatically.