Appearance
6.4.8 — Context and Zustand, Step by Step
The same shop cart, one more time. On page 6.4.7 you built it with Redux Toolkit. Redux is powerful, but for a small or medium app it is a lot of structure.
This page builds the same cart with the two lighter tools: Context, which ships inside React, and Zustand, a tiny library. You will see exactly what each one costs, what each one gets wrong when pushed too far, and how to choose.
1. The problem both tools solve
You already know the problem from page 6.4.3: prop drilling. A value lives at the top, and a component deep inside needs it. Every component in between must carry it as a prop, even though they never use it.
Left: the cart is handed down through Layout, Sidebar and Menu, who do not care about it. If you later rename the prop or add a second value, you must edit every layer. Right: the value is put in one place, and the component that wants it reaches up and takes it directly.
2. Context, step by step
Context is React's built-in way to make a value available to a whole part of the tree without passing props. It has three steps: create it, provide a value, read the value.
We start with the best use of Context: something that changes rarely and is needed everywhere, such as the colour theme.
tsx
// src/theme/ThemeContext.tsx
import { createContext, useContext, useState } from 'react'
import type { ReactNode } from 'react'
type Theme = 'light' | 'dark'
type ThemeValue = {
theme: Theme
toggleTheme: () => void
}
const ThemeContext = createContext<ThemeValue | null>(null) // (1)
export function ThemeProvider({ children }: { children: ReactNode }) { // (2)
const [theme, setTheme] = useState<Theme>('light')
const value: ThemeValue = {
theme,
toggleTheme: () => setTheme((t) => (t === 'light' ? 'dark' : 'light')),
}
return <ThemeContext value={value}>{children}</ThemeContext> // (3)
}
export function useTheme(): ThemeValue { // (4)
const value = useContext(ThemeContext)
if (value === null) {
throw new Error('useTheme must be used inside a ThemeProvider')
}
return value
}createContextmakes the context. The argument is the default value, used when a component asks for the context but no provider is above it. We givenullon purpose, so that forgetting the provider is detectable.ThemeProvideris our own component. It owns the real state withuseState. Context itself stores nothing. It only carries a value down.<ThemeContext value={value}>provides the value to everything inside it. (In React 18 and older you wrote<ThemeContext.Provider value={value}>. React 19 allows the shorter form, and the old one still works.)childrenis "whatever is placed between the opening and closing tags", as on page 6.4.1.useThemeis a small custom hook (a function that starts withuseand calls other hooks) that reads the context and throws a clear error if the provider is missing. Components then calluseTheme()and get a value that is nevernull. Without this, every component would have to check fornull.
Use it like this:
tsx
// src/App.tsx
import { ThemeProvider, useTheme } from './theme/ThemeContext'
function ThemeButton() {
const { theme, toggleTheme } = useTheme() // (1)
return <button onClick={toggleTheme}>Theme: {theme}</button>
}
export default function App() {
return (
<ThemeProvider> {/* (2) */}
<ThemeButton />
</ThemeProvider>
)
}- Any component below the provider, at any depth, can call
useTheme(). - The provider wraps the part of the app that needs the value. Usually it wraps the whole app.
When toggleTheme is called, the provider's state changes, the provider re-renders, it creates a new value, and every component that called useTheme() re-renders with it.
The catch: context cannot select
That last sentence is the whole weakness of Context. A component that reads a context re-renders whenever the context's value changes, even if it only uses one small part of it.
Imagine we put the theme and the cart in one context value. A Chart component reads only the theme. A Badge reads only the cart. The customer adds an item, so the value changes, so both re-render. We measured exactly this: after one cart change, the chart that only wanted the theme rendered again.
For a theme, which changes a few times per visit, this does not matter. For a cart, or anything that changes on every keystroke, it adds up. There are three honest ways to deal with it:
- Split into several contexts, one per kind of data (
ThemeContext,CartContext,UserContext), so a change in one does not wake readers of the others. - Separate the data from the actions. The actions (
addItem) never change, but the data does. Put them in two contexts, and a button that only callsaddItemwill not re-render when the data changes. - Use a store with selectors, which is what Redux and Zustand are.
One more thing people try: useMemo on the value. It helps in one narrow case, which is when the provider's parent re-renders but the value did not really change. It does not stop re-renders caused by the value actually changing.
What Context is good for
Context is best at dependency injection: handing a stable dependency to a whole subtree without threading it through props. The classic cases are the colour theme, the current language, the logged-in user, and "which database or API client should I use". These change rarely, and many components need them. For everything that changes often, use a store.
3. Zustand, step by step
Zustand (German for "state") is a very small library. You make a store, which is a plain object that holds state and the functions that change it. Then you read from it with a hook. There is no provider, and components can pick exactly the values they need.
Install it:
bash
npm install zustandStep 1: create the store
ts
// src/stores/cartStore.ts
import { create } from 'zustand'
export type CartItem = {
productId: string
name: string
priceCents: number
quantity: number
}
type CartStore = {
items: CartItem[] // (1)
addItem: (product: Omit<CartItem, 'quantity'>) => void // (2)
removeItem: (productId: string) => void
clear: () => void
}
export const useCartStore = create<CartStore>()((set) => ({ // (3)
items: [],
addItem: (product) =>
set((state) => { // (4)
const existing = state.items.find((i) => i.productId === product.productId)
if (existing) {
return {
items: state.items.map((i) =>
i.productId === product.productId ? { ...i, quantity: i.quantity + 1 } : i,
),
}
}
return { items: [...state.items, { ...product, quantity: 1 }] }
}),
removeItem: (productId) =>
set((state) => ({ items: state.items.filter((i) => i.productId !== productId) })),
clear: () => set({ items: [] }), // (5)
}))- The data and the actions live side by side in one type. There is no separate "action" object and no reducer. An action is just a function.
- Each action is a normal function property.
createmakes the store and returns a hook. By convention the name starts withuse. The extra()aftercreate<CartStore>is a TypeScript detail that Zustand needs so that it can work out the types of middleware. Write it exactly like this.setis the function that changes the state.setaccepts a function that gets the currentstateand returns the part you want to change. Zustand merges it into the state. You do not return the whole state, only the fields that change. (This is different from React'suseState, whose setter replaces.) You still must not changestatein place: build new arrays and objects, as on page 6.4.2.- When the change does not depend on the old state, pass an object directly.
Compare this with page 6.4.7: no Provider, no configureStore, no typed hooks, no action types. It is about a third of the code.
Step 2: use it in components
tsx
// src/components/Header.tsx
import { useCartStore } from '../stores/cartStore'
export function Header() {
const itemCount = useCartStore((state) =>
state.items.reduce((sum, i) => sum + i.quantity, 0), // (1)
)
return <header>My Shop · Cart: {itemCount}</header>
}tsx
// src/components/ProductCard.tsx
import { useCartStore } from '../stores/cartStore'
type Product = { id: string; name: string; priceCents: number }
export function ProductCard({ product }: { product: Product }) {
const addItem = useCartStore((state) => state.addItem) // (2)
return (
<article>
<h2>{product.name}</h2>
<button
onClick={() =>
addItem({ productId: product.id, name: product.name, priceCents: product.priceCents })
}
>
Add to cart
</button>
</article>
)
}- The function you pass to the hook is a selector, exactly as in Redux. The component re-renders only when the value it returns changes.
ProductCardselects only theaddItemfunction. That function never changes, soProductCardnever re-renders because of the cart. We measured it: when the cart changed, a component that selected the theme rendered zero extra times and the badge rendered once.
Nothing wraps the app. You can import the hook anywhere and it works.
The one trap: selecting an object
In Zustand 5, this looks natural and is a bug:
tsx
// Wrong: returns a NEW object on every call
const { items, clear } = useCartStore((state) => ({ items: state.items, clear: state.clear }))Zustand decides whether to re-render by comparing the selector's result with ===. A fresh object is never === the last one, so it always looks changed. In version 5 this is not just slow: React ends up in a loop and throws "Maximum update depth exceeded". We reproduced that error.
There are two fixes. The simple one is to select each value on its own line:
tsx
const items = useCartStore((state) => state.items)
const clear = useCartStore((state) => state.clear)The other is useShallow, which compares the fields of the returned object one by one instead of the object itself:
tsx
import { useShallow } from 'zustand/react/shallow'
const { items, clear } = useCartStore(useShallow((state) => ({ items: state.items, clear: state.clear })))Step 3: use it outside React
The store is an ordinary object, so code that is not a component can use it. This is something Redux makes harder and Context cannot do at all.
ts
// src/lib/socket.ts
import { useCartStore } from '../stores/cartStore'
export function onCartChangedElsewhere(productId: string) {
useCartStore.getState().addItem({ productId, name: 'Synced item', priceCents: 0 }) // (1)
}
const unsubscribe = useCartStore.subscribe((state, previous) => { // (2)
console.log(`cart items: ${previous.items.length} → ${state.items.length}`)
})
// call unsubscribe() when you no longer want to listengetState()reads the current state, and the actions inside it work too. Handy for a WebSocket message or a timer.subscribecalls your function after every change, with the new and the previous state. In our run, adding one product printedcart items: 1 → 2.
Use this sparingly. It is easy to make a mess if every file changes the store, so keep real changes inside the store's own actions.
Step 4: save the state across page reloads
The cart should still be there if the customer refreshes the page. Zustand's persist middleware does it. (A middleware is a wrapper around the store that adds a feature.)
ts
// src/stores/cartStore.ts (persisted version)
import { create } from 'zustand'
import { persist } from 'zustand/middleware'
type CartItem = { productId: string; name: string; priceCents: number; quantity: number }
type CartStore = { items: CartItem[]; clear: () => void }
export const useCartStore = create<CartStore>()(
persist(
(set) => ({
items: [],
clear: () => set({ items: [] }),
}),
{
name: 'cart', // (1)
partialize: (state) => ({ items: state.items }), // (2)
},
),
)nameis the key in the browser'slocalStorage(a small key-value store that survives reloads).partializechooses what to save. We save only the data, not the functions. We checked what lands in storage:{"state":{"n":2},"version":0}, a plain JSON object with a version number.
Two warnings, both explained in page 6.4.6. A persisted store can cause a "hydration mismatch" if the page is rendered on a server, because the server has no localStorage. And a store defined at module level on a server is shared between visitors. If you build with a framework that renders on a server (Chapter 6.5), read those sections first.
4. The same cart in three tools
| Context | Redux Toolkit | Zustand | |
|---|---|---|---|
| Amount of code for the cart | moderate | most (several files) | least (one file) |
| Needs a Provider | yes | yes | no |
| Re-renders only what changed | no | yes | yes |
| Works outside components | no | yes (store.dispatch) | yes (getState) |
| Debug tool | React DevTools | Redux DevTools (time travel) | Redux DevTools (optional) |
| Learning curve | lowest | steepest | low |
And how to choose:
- Theme, language, current user, an API client: Context. It changes rarely, and it is already in React.
- A cart, a shopping filter, a drawer being open, anything that changes often and many components read: a store. Zustand for most apps.
- A large app with many teams that wants one strict pattern and a visible action log: Redux Toolkit.
- Products, orders, anything that lives on a server: none of these. Use TanStack Query (pages 6.4.10 and 6.4.11).
- What page you are on, the current filter, the sort order: the URL (pages 6.4.9 and 6.4.12).
Most apps use two or three of these together. That is normal.
What the interviewer will push on
"What is Context for, and when does it hurt performance?" It carries a value down the tree without props. Every component that reads it re-renders when the value changes, and a component cannot read only part of it. So it suits rarely changing values, and hurts for fast-changing ones. Add the fixes: split contexts, separate actions from data, or use a store with selectors.
"What is prop drilling, and how do you avoid it?" Passing a value through layers that do not use it. Fix by lifting less, composing with children, Context, or a store. Naming children composition shows you are not reaching for global state by reflex.
"How is Zustand different from Redux?" No provider, no reducers or action types, state and actions in one object, selectors for fine-grained updates. Less structure and less tooling. Redux gives a strict pattern and strong DevTools. They both use the same React hook underneath (useSyncExternalStore, page 6.4.5), which makes them safe with concurrent rendering.
"Why does my Zustand component loop forever?" A selector that returns a new object every time (in version 5). Select single values, or use useShallow.
"Where do you keep server data: Context, Redux or Zustand?" In none of them. In a server-data cache such as TanStack Query. This answer is what the question is checking.
"How would you persist state?" The persist middleware, with partialize to save only the data. Then mention the server-rendering hydration issue.
One thing to volunteer: say that you would first try to keep the state local, then lift it, and only then reach for Context or a store. It signals that you do not use global state as a default.
Recall
- Prop drilling is passing a value through layers that do not use it. Context and stores remove it.
- Context in three steps:
createContext(default)→ a provider component that owns the state and renders<Ctx value={…}>→ components calluseContext(Ctx). WrapuseContextin a custom hook that throws if the provider is missing. - Context cannot select. Every reader re-renders when the value changes. Fine for the theme, language, user. Bad for fast-changing data. Fixes: split contexts, separate actions from data, or use a store.
- Zustand:
create<State>()((set) => ({ data, actions }))returns a hook.setmerges the fields you return. No provider. Read with a selector:useStore((s) => s.items). Only components whose selected value changed re-render. - Zustand 5 trap: a selector that returns a new object each time loops with "Maximum update depth exceeded". Select values separately, or wrap with
useShallow. - Outside React:
store.getState()andstore.subscribe(fn). persistmiddleware saves tolocalStorage.partializepicks what to save. Beware the server hydration mismatch.- Choosing: rarely changing values → Context. Frequently changing shared client state → Zustand (or Redux Toolkit for big, strict teams). Server data → TanStack Query. Page, filter, sort → the URL.
Self-test: Why does a chart that only reads the theme redraw when the cart changes, with one shared context? · What does set do with the object you return? · Why does useCartStore((s) => ({ a: s.a })) break in version 5? · Name two things Zustand can do that Context cannot. · Where does a product list belong?
Next: 6.4.9 is about the one piece of state every web app has and which does not belong in a store: which page the user is looking at. It teaches React Router, step by step.