State management in React
State management in React refers to how you store, update, and share data across components in a React application. Managing state effectively is crucial for building responsive, maintainable apps — especially as your app grows.
🧠 What is State in React?
In React, state is data that determines how your UI behaves. When state changes, the UI updates.
There are two main types of state:
Type | Description |
---|---|
Local state | State owned by a single component (useState ) |
Global state | Shared across multiple components (via Context, Redux, etc.) |
🔹 1. Local State Management
Use React Hooks like useState
and useReducer
to manage local state.
const [count, setCount] = useState(0);
For more complex logic:
const [state, dispatch] = useReducer(reducerFunction, initialState);
🔹 2. Global State Management
Used when you need to share state between many components. Options include:
✅ React Context API
- Built-in solution
- Works well for simple global data (like theme, user info, etc.)
const UserContext = React.createContext();
<UserContext.Provider value={user}>
<Child />
</UserContext.Provider>
Access it with useContext(UserContext)
.
✅ Third-party Libraries
Library | When to Use |
---|---|
Redux | For large apps with complex global state, actions, reducers |
Zustand | Simpler alternative to Redux, minimal and fast |
Recoil | Built by Facebook, supports atom-based state model |
MobX | Observable state, automatic tracking of dependencies |
Jotai | Primitive and modern global state library |
XState | Based on state machines, for apps with well-defined transitions |
🔸 3. Derived State
Sometimes you calculate state based on other state or props.
Use:
const filteredItems = items.filter(item => item.active);
Or memoize for performance:
const filteredItems = useMemo(() => {
return items.filter(item => item.active);
}, [items]);
🔸 4. Server State
State that comes from a server (e.g., API data). Managed via:
useEffect
+fetch
oraxios
- React Query, SWR, Apollo Client for powerful caching, revalidation, pagination, etc.
🔸 5. URL State
URL-related data (like query parameters, pathname) is also state.
Managed via:
react-router-dom
useSearchParams
,useLocation
,useNavigate
🧩 Summary Table
Type | Tools/Methods |
---|---|
Local state | useState , useReducer |
Global state | Context API, Redux, Zustand, etc. |
Derived state | useMemo , inline calculations |
Server state | React Query, Axios + useEffect |
URL state | React Router |
🔍 Tips for Effective State Management
- Keep state close to where it’s needed
- Don’t overuse global state
- Use
useReducer
for complex updates - Prefer libraries (like React Query) for server state
- Don’t store derived data in state — compute it when needed
Comments are closed.