Sub topic 1
Why Zustand and when to reach for it
Prerequisites
This chapter assumes you can:
- Write React function components and use
useStateanduseEffect. - Read basic TypeScript or JavaScript: modules, arrow functions, and object spread.
- Explain prop drilling, which is passing a value through several components that don't use it just to reach one that does.
- Update objects and arrays without mutating them, for example
{ ...state, count: 1 }.
You don't need to know Redux or Context in depth. Where they come up, the chapter describes only what matters for the comparison.
The problem Zustand solves
Local state with useState works until two distant components need the same value. You then have three common options:
- Lift the state to a shared parent and pass it down as props. This gets tedious as the tree grows.
- Put the state in React Context. This removes the drilling, but it has a re-render cost, described below.
- Use an external state library.
Zustand is in the third group. It keeps state in a store, a plain JavaScript object that lives outside the React tree. Components subscribe to the parts of the store they need. The store is created with a single function call, and no provider component is required in the basic case.
The name is German for "state". The library is small, and its API is mostly one function, create.
The working model
Three ideas explain most of Zustand's behavior.
- The store is a closure holding state. Calling
createreturns a React hook. The state lives in a module-level closure, not in a component. - Components subscribe through selectors. A selector is a function that picks a value out of the state. A component re-renders only when the value its selector returns changes.
- State changes go through
set.setmerges a partial object into the current state and notifies subscribers. Actions are ordinary functions stored in the same object as the data.
The next diagram shows how a click travels through those pieces.
The key point is the last two steps. The store notifies every subscriber, but each subscriber compares the old and new selector results and re-renders only on a difference. The next chapters cover this in detail.
A first look
You will build this properly in the next chapter. For now, read it to see how little code is involved.
import { create } from 'zustand'
interface CounterState {
count: number
increment: () => void
reset: () => void
}
export const useCounterStore = create<CounterState>()((set) => ({
count: 0,
increment: () => set((state) => ({ count: state.count + 1 })),
reset: () => set({ count: 0 }),
}))State and actions sit side by side in one object. set receives either a partial object or a function that takes the current state and returns a partial object. Either way, Zustand merges the result into the existing state.
A component reads from the store by passing a selector to the hook:
import { useCounterStore } from './counterStore'
function Count() {
const count = useCounterStore((state) => state.count)
return <p>Count: {count}</p>
}
function Controls() {
const increment = useCounterStore((state) => state.increment)
return <button onClick={increment}>Add one</button>
}Controls selects only the increment function. That function never changes, so Controls does not re-render when count changes. There is no provider to mount, so both components work wherever you render them.
How Zustand compares with the alternatives
The choice depends on what kind of state you have and how much structure your team wants.
| Option | Strengths | Costs |
|---|---|---|
| `useState` plus props | No dependencies, easy to trace | Prop drilling across many levels |
| React Context | Built in, good for values that rarely change | Every consumer re-renders when the context value changes, and you write the provider and update logic yourself |
| Redux Toolkit | Strict structure, mature tooling, large ecosystem | More concepts and boilerplate: slices, reducers, a provider |
| Zustand | Small API, no provider needed, selector-based re-renders | Little enforced structure, so conventions are up to you |
Why Context re-renders more
When a Context value changes, React re-renders every component that calls useContext on it. It does this even if a component uses only one field of an object value. You can reduce the effect by splitting contexts or memoizing, but that adds code. Zustand moves the comparison into the subscription itself, so a component that selects count ignores changes to other fields.
Zustand and Redux
Both keep state outside components and update it through defined actions. Zustand drops the requirement for action types, reducers, and a provider. You call set inside an action. Zustand does support Redux DevTools, and it ships a redux middleware if you want reducer-style updates. If your team benefits from a rigid, uniform pattern across a large codebase, Redux Toolkit may suit it better.
When to reach for Zustand
Zustand fits well when:
- Several components in different parts of the tree share client-side state, such as a shopping cart, UI toggles, or user preferences.
- You want state and the functions that change it in one place.
- You want to read or change state from outside React, for example in an event handler set up in plain JavaScript.
- You want a small dependency and a short learning curve.
The following callout covers a common mistake about scope.
When it is the wrong tool
Skip Zustand, or use it sparingly, in these cases:
- State used by one component or a small subtree.
useStateis simpler. A global store adds indirection for no benefit. - Server data with caching needs. Use a dedicated data-fetching library.
- Values that rarely change and are read by many components, such as a theme or locale. Context handles these well.
- Server-side rendering with per-request state. A module-level store is shared across requests on the server, so one user's state could leak into another's. The safe approach is a store created per request and passed through Context. A later chapter covers this pattern.
Zustand also does not enforce structure. Two developers can organize stores very differently. If your team needs a single prescribed pattern, decide on conventions early, such as one store per feature and a naming rule for actions.
Common misconceptions
- "Zustand replaces
useState." It does not. Keep local state local. - "The store is reactive on its own." Only components that call the hook subscribe. Plain code that reads
getState()gets a snapshot and is not notified of later changes unless you callsubscribe. - "Mutating state is fine because it's just an object." Zustand compares by reference. If you mutate an object and call
setwith the same reference, subscribers may not see a change. Update immutably, or use theimmermiddleware covered later.
What the next chapters cover
The sequence builds on this overview: creating a store, reading with selectors, updating with set, controlling re-renders, async actions, TypeScript, middleware, and testing. The final chapter returns to the decision of when Zustand is the wrong choice, with more edge cases.
Exercise
A dashboard has a theme setting that changes about once a month and is read by 200 components. A separate shopping cart changes often and is read by five components in different parts of the tree. Which of the two is the stronger candidate for Zustand, and why?
Show answer
The shopping cart. It changes often and is shared across distant components, so selectors that limit re-renders matter. The theme changes rarely, so Context's re-render cost is small, and Context is built in. Zustand could still hold the theme, but it offers little advantage there.
Exercise
A component calls useCounterStore((state) => state.increment). A different component then calls increment(), which changes count. Does the first component re-render, and why?
Show answer
No. Its selector returns the increment function, and that function's reference is the same before and after the update. Zustand compares the old and new selector results, finds them equal, and skips the render.