Home / Learn React / State Management: Context, Zustand and Redux Toolkit
State Management: Context, Zustand and Redux Toolkit
Small apps need only useState. When many far-apart components share data you can use Context with a reducer, or a library such as Zustand or Redux Toolkit.
Theory in plain words
What it is
State management is the way an app stores and shares data that many components need: the logged-in user, a cart, theme or filters.
Why we use it
Passing props through many levels (prop drilling) is tedious, and Context re-renders every consumer when its value changes. Libraries give selective updates and tooling.
How it works
Context broadcasts a value. A store library keeps state outside React and lets each component subscribe only to the part it reads.
Where it is used
- Shopping carts, auth, dashboards, editors, collaborative apps
npm install zustand
import { create } from "zustand";
const useCart = create(set => ({
items: [],
add: name => set(s => ({ items: [...s.items, name] })),
}));
function Badge() {
const count = useCart(s => s.items.length); // re-renders only when the count changes
return <span>{count}</span>;
}npm install @reduxjs/toolkit react-redux
import { configureStore, createSlice } from "@reduxjs/toolkit";
const cart = createSlice({
name: "cart", initialState: { items: [] },
reducers: { add: (s, a) => { s.items.push(a.payload); } }, // "mutation" is safe here (Immer)
});
export const { add } = cart.actions;
export const store = configureStore({ reducer: { cart: cart.reducer } });| Option | Best for | Watch out |
|---|---|---|
| useState | One component | Prop drilling if shared widely |
| Context + reducer | Theme, user, small apps | All consumers re-render on change |
| Zustand | Medium apps, simple API | Fewer conventions |
| Redux Toolkit | Big teams, devtools, strict patterns | More boilerplate |
| TanStack Query | Server data (not UI state) | Do not copy server data into other stores |
Quick quiz
1. Which is best for a single component counter?
Keep it local.
2. A downside of Context for fast changing data?
Every consumer re-renders when the value changes.
3. TanStack Query is mainly for...
It caches and refetches server data.
Common questions
Which is best for a single component counter?
useState. Keep it local.
A downside of Context for fast changing data?
All consumers re-render. Every consumer re-renders when the value changes.