Sub topic 3
Reading state with selectors
This chapter assumes you know React function components and hooks, basic TypeScript or JavaScript, and what a Zustand store looks like after create. You will learn how a selector decides what a component reads and when it re-renders.
What a selector is
A selector is a function that takes the whole store state and returns the part a component needs. You pass it to the hook that create returned:
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>
}Count reads count. Controls reads the increment action. When count changes, Count re-renders and Controls does not, because the value Controls selected is still the same function.
How Zustand uses the selector
Each time the store changes, Zustand runs your selector on the new state. It then compares the result to the previous result with Object.is. If the two are equal, the component skips the re-render. If they differ, React re-renders it.
The diagram below shows this flow.
Two consequences follow from this model:
- The selector runs on every store update for every subscribed component, so keep selectors cheap.
- What matters is the selector's return value, not the part of the state that changed. A component that selects
state.countignores changes to every other field.
Selecting a single value versus the whole store
Calling the hook without a selector returns the entire state:
const { count, increment } = useCounterStore()This works, but the component now re-renders on every change to any field. In a small store this is harmless. As the store grows, it becomes a common source of wasted renders. Prefer one selector per value:
const count = useCounterStore((state) => state.count)
const increment = useCounterStore((state) => state.increment)Calling the hook several times is fine. Each call subscribes to its own slice of the state, and React batches the resulting updates.
Selecting actions
Actions defined inside the store are created once and keep the same identity for the life of the store. A selector that returns an action therefore never triggers a re-render. This is why Controls above stays quiet while the count changes. Selecting actions separately from data is a good habit, since actions never cause renders and data does.
Selectors that return objects
Selectors that build a new object or array each time are a trap. This one returns a fresh object on every call:
// Problem: new object each time, so Object.is is always false
const { name, email } = useUserStore((state) => ({
name: state.name,
email: state.email,
}))The comparison with Object.is fails on every store update, because two separate object literals are never the same reference. The component re-renders on every change to the store, even when name and email did not change. With Zustand 5 (which uses React's useSyncExternalStore), returning an unstable reference from a selector can also cause an "Maximum update depth exceeded" error, because React sees the snapshot change on every check.
There are two ways to avoid this. The first is to select primitives separately:
const name = useUserStore((state) => state.name)
const email = useUserStore((state) => state.email)The second is useShallow, which compares the top-level fields of the returned object instead of its reference:
import { useShallow } from 'zustand/react/shallow'
import { useUserStore } from './userStore'
function Profile() {
const { name, email } = useUserStore(
useShallow((state) => ({ name: state.name, email: state.email })),
)
return <p>{name} ({email})</p>
}Now Profile re-renders only when name or email changes. The next chapter covers useShallow in more detail. For now, remember the rule: if a selector builds a new object or array, wrap it in useShallow.
Selecting from nested state
A selector can reach into nested objects:
const theme = useSettingsStore((state) => state.preferences.theme)The component re-renders only when theme changes. If you replace preferences with a new object that has the same theme, the selected string is equal and no render occurs. Select the narrowest value you can.
Selectors with arguments
Sometimes the selector depends on a prop, such as an ID. Define the selector inline so it closes over the prop:
function TodoTitle({ id }: { id: number }) {
const title = useTodoStore(
(state) => state.todos.find((t) => t.id === id)?.title,
)
return <h3>{title}</h3>
}This returns a string or undefined, both stable values, so it behaves well. The selector is a new function on each render, which is fine. Zustand calls the latest one, and only the returned value is compared.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| Component re-renders on every store change | No selector, or the selector returns a new object or array | Select primitives, or use `useShallow` |
| "Maximum update depth exceeded" | Selector returns a new reference on each call (Zustand 5) | Use `useShallow` or select stable values |
| Component never updates | Store state was mutated in place, so the selected reference did not change | Update with `set` and return new objects |
| Stale value inside an event handler | Value captured from an old render | Read fresh state with `useStore.getState()` in the handler |
When not to select
If a value is needed only inside an event handler and the component does not display it, you do not need to subscribe. Reading it with getState() avoids subscribing the component at all:
import { useCounterStore } from './counterStore'
function LogButton() {
const handleClick = () => {
console.log(useCounterStore.getState().count)
}
return <button onClick={handleClick}>Log count</button>
}LogButton never re-renders when the count changes, and the log always shows the current value.
Summary of rules
- Pass a selector to the hook, and select the smallest value you need.
- Selectors compare results with
Object.is, so primitives and stable references skip re-renders. - Selectors that build new objects or arrays need
useShallow. - Select actions on their own. They never cause re-renders.
- Use
getState()for values needed only in handlers.
Exercise
A component calls const { items, total } = useCartStore((state) => ({ items: state.items, total: state.total })). It re-renders whenever any unrelated field in the cart store changes. Why does this happen, and how do you fix it?
Show answer
The selector returns a new object literal on every call. Zustand compares results with Object.is, and two different object references are never equal, so the component re-renders on every store update. Fix it by wrapping the selector in useShallow, which compares items and total individually, or by calling the hook twice with (state) => state.items and (state) => state.total.
Exercise
Why does a component that selects only an action, such as useCounterStore((state) => state.increment), never re-render when the count changes?
Show answer
The action function is created once when the store is created and keeps the same reference. The selector returns that same reference after each update, so the Object.is check passes and React skips the render.