Context and State Management · Lesson 20 of 31
React State Management: Context, Zustand, Redux
"Which state management library should I use?" is one of the most asked React questions. The honest answer: most state doesn't need a library. This lesson sorts state into types, shows the built-in Context + useReducer pattern, and then the two most popular libraries – Zustand and Redux Toolkit – with the same cart in each, so you can compare.
In this lesson
- The four kinds of state
- Context + useReducer for app-wide state
- The same cart with Zustand and with Redux Toolkit
- Server state belongs in TanStack Query
Four kinds of state
| Kind | Examples | Where it should live |
|---|---|---|
| Local UI state | input text, open/closed, selected tab | useState in the component |
| Shared UI state | theme, current user, cart, sidebar open | lifted state, Context, or a store (Zustand/Redux) |
| Server state | courses, profile, orders from an API | TanStack Query, SWR, or framework loaders |
| URL state | search query, filters, page number | the URL (React Router's useSearchParams) |
Once server data moves into a query library and filters move into the URL, the "global state" left over is usually small.
Context + useReducer
import { createContext, useContext, useReducer } from "react";
const CartContext = createContext(null);
function cartReducer(items, action) {
switch (action.type) {
case "added":
return items.some((i) => i.id === action.item.id)
? items.map((i) => (i.id === action.item.id ? { ...i, qty: i.qty + 1 } : i))
: [...items, { ...action.item, qty: 1 }];
case "cleared":
return [];
default:
throw new Error(action.type);
}
}
function CartProvider({ children }) {
const [items, dispatch] = useReducer(cartReducer, []);
return <CartContext value={{ items, dispatch }}>{children}</CartContext>;
}
const useCart = () => useContext(CartContext);
function CartBadge() {
const { items } = useCart();
return <p>🛒 Cart: {items.reduce((n, i) => n + i.qty, 0)}</p>;
}
function ProductButton({ product }) {
const { dispatch } = useCart();
return <button onClick={() => dispatch({ type: "added", item: product })}>Add {product.name}</button>;
}
export default function App() {
return (
<CartProvider>
<CartBadge />
<ProductButton product={{ id: 1, name: "React course" }} />
<ProductButton product={{ id: 2, name: "Next.js course" }} />
</CartProvider>
);
}
🛒 Cart: 0 [Add React course] [Add Next.js course] › click “Add React course” 🛒 Cart: 1 [Add React course] [Add Next.js course] › click “Add React course” 🛒 Cart: 2 [Add React course] [Add Next.js course] › click “Add Next.js course” 🛒 Cart: 3 [Add React course] [Add Next.js course]
No dependencies, easy to test. The drawback: every component using useCart() re-renders whenever the cart changes – fine for small apps, noticeable in large ones.
Zustand: a tiny store with selectors
Zustand (npm i zustand) is a small library for shared state. A store is a hook; components select just the piece they need and only re-render when that piece changes. No provider is needed.
import { create } from "zustand";
const useCartStore = create((set) => ({
items: [],
add: (product) =>
set((state) => {
const found = state.items.find((i) => i.id === product.id);
return {
items: found
? state.items.map((i) => (i.id === product.id ? { ...i, qty: i.qty + 1 } : i))
: [...state.items, { ...product, qty: 1 }],
};
}),
clear: () => set({ items: [] }),
}));
function CartBadge() {
const count = useCartStore((s) => s.items.reduce((n, i) => n + i.qty, 0)); // selector
return <p>🛒 Cart: {count}</p>;
}
function ProductButton({ product }) {
const add = useCartStore((s) => s.add); // actions never change, so this never re-renders
return <button onClick={() => add(product)}>Add {product.name}</button>;
}
function ClearButton() {
const clear = useCartStore((s) => s.clear);
return <button onClick={clear}>Clear cart</button>;
}
export default function App() {
return (
<>
<CartBadge />
<ProductButton product={{ id: 1, name: "React course" }} />
<ProductButton product={{ id: 2, name: "Next.js course" }} />
<ClearButton />
</>
);
}
🛒 Cart: 0 [Add React course] [Add Next.js course] [Clear cart] › click “Add React course” 🛒 Cart: 1 [Add React course] [Add Next.js course] [Clear cart] › click “Add Next.js course” 🛒 Cart: 2 [Add React course] [Add Next.js course] [Clear cart] › click “Clear cart” 🛒 Cart: 0 [Add React course] [Add Next.js course] [Clear cart]
Redux Toolkit: structure for large teams
Redux Toolkit (npm i @reduxjs/toolkit react-redux) is the official, modern way to write Redux. createSlice generates action creators, and you can write reducers in a "mutating" style because Immer turns them into immutable updates:
import { configureStore, createSlice } from "@reduxjs/toolkit";
import { Provider, useDispatch, useSelector } from "react-redux";
const cartSlice = createSlice({
name: "cart",
initialState: { items: [] },
reducers: {
added(state, action) {
const found = state.items.find((i) => i.id === action.payload.id);
if (found) found.qty += 1; // looks like mutation – Immer makes it immutable
else state.items.push({ ...action.payload, qty: 1 });
},
cleared(state) {
state.items = [];
},
},
});
const { added, cleared } = cartSlice.actions;
const store = configureStore({ reducer: { cart: cartSlice.reducer } });
function CartBadge() {
const count = useSelector((state) => state.cart.items.reduce((n, i) => n + i.qty, 0));
return <p>🛒 Cart: {count}</p>;
}
function ProductButton({ product }) {
const dispatch = useDispatch();
return <button onClick={() => dispatch(added(product))}>Add {product.name}</button>;
}
export default function App() {
return (
<Provider store={store}>
<CartBadge />
<ProductButton product={{ id: 1, name: "React course" }} />
<ProductButton product={{ id: 2, name: "Next.js course" }} />
<button onClick={() => store.dispatch(cleared())}>Clear cart</button>
</Provider>
);
}
🛒 Cart: 0 [Add React course] [Add Next.js course] [Clear cart] › click “Add React course” 🛒 Cart: 1 [Add React course] [Add Next.js course] [Clear cart] › click “Add React course” 🛒 Cart: 2 [Add React course] [Add Next.js course] [Clear cart] › click “Add Next.js course” 🛒 Cart: 3 [Add React course] [Add Next.js course] [Clear cart] › click “Clear cart” 🛒 Cart: 0 [Add React course] [Add Next.js course] [Clear cart]
Redux adds more ceremony, and in return gives you strict structure, excellent DevTools (time-travel debugging, action logs), middleware, and RTK Query for data fetching. That's why it's still common in large enterprise codebases.
Server state: TanStack Query
Data from an API isn't really "your" state – it's a cache of the server's. Storing it in Redux or Zustand means hand-writing loading flags, caching and refetching. A query library does all of that:
import { QueryClient, QueryClientProvider, useQuery } from "@tanstack/react-query";
const queryClient = new QueryClient();
// fake API for the demo
const fetchCourses = () =>
new Promise((resolve) => setTimeout(() => resolve(["React.js", "Next.js", "TypeScript"]), 200));
function Courses() {
const { data, isPending, isFetching } = useQuery({ queryKey: ["courses"], queryFn: fetchCourses });
if (isPending) return <p>Loading courses…</p>;
return <p>{data.join(", ")}{isFetching ? " (refreshing)" : ""}</p>;
}
export default function App() {
return (
<QueryClientProvider client={queryClient}>
<Courses />
<Courses /> {/* same key: one request, shared cache */}
</QueryClientProvider>
);
}
Loading courses… Loading courses… › wait 250ms React.js, Next.js, TypeScript React.js, Next.js, TypeScript
How to choose
- Start with useState and lift state when needed.
- Put API data in TanStack Query (or your framework's data loading) and filters in the URL.
- For a few app-wide values that change rarely, use Context (+ useReducer).
- For frequently-changing shared state, pick Zustand (small, simple) or Redux Toolkit (structure, DevTools, large teams).
Practice
Try it yourself
With Zustand, make a store for a notifications count with
incrementandmarkAllRead, used by two separate components.Show solution
import { create } from "zustand"; const useNotifications = create((set) => ({ unread: 3, increment: () => set((s) => ({ unread: s.unread + 1 })), markAllRead: () => set({ unread: 0 }), })); function Bell() { const unread = useNotifications((s) => s.unread); return <p>🔔 {unread}</p>; } function Controls() { const { increment, markAllRead } = useNotifications(); return ( <> <button onClick={increment}>New message</button> <button onClick={markAllRead}>Mark all read</button> </> ); } export default function App() { return ( <> <Bell /> <Controls /> </> ); }🔔 3 [New message] [Mark all read] › click “New message” 🔔 4 [New message] [Mark all read] › click “Mark all read” 🔔 0 [New message] [Mark all read]
Quick check
Where should data fetched from an API live?
In a server-state cache such as TanStack Query (or framework loaders), not hand-managed global state.
Why can Zustand avoid unnecessary re-renders?
Components subscribe with selectors and only re-render when the selected value changes.
Why can Redux Toolkit reducers "mutate" state?
Immer records the changes and produces a new immutable state.
Summary
- Separate local, shared, server and URL state – most of it needs no library.
- Context + useReducer covers small apps; Zustand and Redux Toolkit scale with selectors.
- Use TanStack Query for server data.
Finished this lesson?
Mark it complete to track your progress, then carry on with the next lesson.