Sub topic 5
Controlling re-renders and using useShallow
This chapter assumes you can write React function components and hooks, and that you have built a Zustand store with create and read it with selectors. Here you will learn exactly when a component re-renders, how selectors that return new objects break that, and how useShallow fixes it.
How Zustand decides to re-render
A component that calls a store hook subscribes to the store. After every set, Zustand runs the component's selector against the new state. It then compares the result with the previous selector result using Object.is. If the two values are the same, the component does not re-render. If they differ, React re-renders it.
This is why selectors matter. The selector defines what the component cares about, and nothing else triggers a render.
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 re-renders whenever count changes. Controls selects a function. The increment function is created once when the store is created, so its reference never changes and Controls does not re-render when count changes.
What Object.is means for your selectors
Object.is compares by identity for objects, arrays and functions. It compares by value for numbers, strings, booleans and null.
| Selector returns | Compared by | Re-renders when |
|---|---|---|
| A number, string or boolean | Value | The value changes |
| A function from the store | Reference | The function is replaced |
| An object or array stored in state | Reference | `set` puts a new object or array in that field |
| A new object or array built in the selector | Reference | Every state change, because it is always new |
The last row is the one that causes trouble.
The new-object trap
Suppose you want name and email from a user store. The natural attempt is to build an object in the selector:
import { useUserStore } from './userStore'
function Profile() {
const { name, email } = useUserStore((state) => ({
name: state.name,
email: state.email,
}))
return <p>{name} ({email})</p>
}Every time the selector runs, it creates a new object. Object.is(oldObject, newObject) is always false, so Zustand treats every store update as a change. Profile re-renders when any field in the store changes, even fields it does not use.
In Zustand v5 the problem is worse. A selector that returns a fresh reference on each call can cause React to report "Maximum update depth exceeded", an infinite render loop, because the hook's snapshot is never stable between reads. In v4 you would typically see only extra renders. Either way, the fix is the same.
Fix 1: select primitives separately
The simplest fix is to call the hook once per value:
import { useUserStore } from './userStore'
function Profile() {
const name = useUserStore((state) => state.name)
const email = useUserStore((state) => state.email)
return <p>{name} ({email})</p>
}Each selector returns a string, which is compared by value. This is easy to read and needs no extra API. It becomes repetitive when you need many fields.
Fix 2: useShallow
useShallow wraps a selector and changes how its result is compared. Instead of Object.is on the whole result, it compares the result's top-level fields one by one. If every field is identical to the previous result, Zustand reuses the previous object, so the reference stays stable and no re-render happens.
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. A change to any other field in the store is ignored.
useShallow also works with arrays, which is useful when you pick several values with a tuple:
import { useShallow } from 'zustand/react/shallow'
import { useUserStore } from './userStore'
function Header() {
const [name, email] = useUserStore(
useShallow((state) => [state.name, state.email]),
)
return <h1>{name} - {email}</h1>
}What "shallow" means
Shallow comparison checks one level deep. For each key, it asks whether the old and new values are the same by Object.is. It does not look inside nested objects.
import { useShallow } from 'zustand/react/shallow'
import { useUserStore } from './userStore'
function Address() {
// address is an object in state, such as { city: string; zip: string }
const { address, name } = useUserStore(
useShallow((state) => ({ address: state.address, name: state.name })),
)
return <p>{name}, {address.city}</p>
}This component re-renders when name changes or when address is replaced with a new object. If a set call keeps the same address reference, it does not re-render. If you update address.city immutably, address becomes a new reference, and the component re-renders as expected.
Selecting a whole store by mistake
Calling the hook without a selector returns the entire state:
import { useCounterStore } from './counterStore'
function Everything() {
const state = useCounterStore()
return <p>{state.count}</p>
}Every set call produces a new state object, so this component re-renders on every change in the store. It is correct but wasteful. Prefer a selector, or useShallow when you need several fields.
Selecting actions
Actions are usually functions defined once inside create, so their references are stable. Selecting an action never causes a re-render by itself. You can group several actions with useShallow if you want one hook call:
import { useShallow } from 'zustand/react/shallow'
import { useCounterStore } from './counterStore'
function Buttons() {
const { increment, reset } = useCounterStore(
useShallow((state) => ({ increment: state.increment, reset: state.reset })),
)
return (
<>
<button onClick={increment}>Add one</button>
<button onClick={reset}>Reset</button>
</>
)
}Selectors that filter or map
Selectors that call filter, map or slice also return new arrays each time. The useShallow wrapper handles this when the items inside are the same references:
import { useShallow } from 'zustand/react/shallow'
import { useTodoStore } from './todoStore'
function DoneTitles() {
const titles = useTodoStore(
useShallow((state) => state.todos.filter((t) => t.done).map((t) => t.title)),
)
return <ul>{titles.map((t) => <li key={t}>{t}</li>)}</ul>
}The array is rebuilt on each run, but its elements are strings, so shallow comparison finds no change unless the list of done titles actually changes.
Common mistakes
- Returning an object or array literal from a plain selector without
useShallow. - Calling
useShallowoutside a hook call. It must be used directly as the argument to the store hook, inside a component or custom hook. - Reading the whole store with no selector, then using one field.
- Expecting
useShallowto detect changes inside nested objects. - Putting expensive work in a selector, which runs after every state update.
Exercise
A component uses useStore((s) => ({ a: s.a, b: s.b })). A different component calls set({ c: 5 }), which changes only a field c. Does the first component re-render, and what change makes it re-render only when a or b change?
Show answer
Yes, it re-renders. The selector returns a new object on every run, so Object.is reports a difference. Wrap the selector in useShallow, as in useStore(useShallow((s) => ({ a: s.a, b: s.b }))), or call the hook twice with (s) => s.a and (s) => s.b.
Exercise
Why does a component that selects only state.increment not re-render when count changes?
Show answer
The selector returns the increment function, which was created once and keeps the same reference. Object.is on the old and new result is true, so Zustand skips the render.