Sub topic 6
Derived state without storing it
This chapter assumes you can create a store with create and read it with selectors. It also assumes you know why selectors affect re-renders.
What derived state is
Derived state is a value you can compute from other state. Examples are the number of unfinished todos, a filtered list, or a cart total. If you store both todos and remainingCount, every action must update both. When one update is forgotten, the two values disagree.
Store the source of truth only. Compute everything else when you read it.
Derive inside a selector
A selector can do the computation. The component re-renders only when the result changes.
import { create } from 'zustand'
interface Todo {
id: number
title: string
done: boolean
}
interface TodoState {
todos: Todo[]
toggle: (id: number) => void
}
const useTodoStore = create<TodoState>()((set) => ({
todos: [
{ id: 1, title: 'Write tutorial', done: false },
{ id: 2, title: 'Review tutorial', done: true },
],
toggle: (id) =>
set((state) => ({
todos: state.todos.map((t) => (t.id === id ? { ...t, done: !t.done } : t)),
})),
}))
function RemainingCount() {
const remaining = useTodoStore((state) => state.todos.filter((t) => !t.done).length)
return <p>{remaining} left</p>
}The selector returns a number. Zustand compares it with Object.is, so toggling a todo that doesn't change the count causes no re-render.
The new-reference trap
The same approach breaks when the selector returns a new array or object. filter creates a new array on every call, so the result is never equal to the previous one.
// Problem: a new array on every call
const open = useTodoStore((state) => state.todos.filter((t) => !t.done))In Zustand v5 this can fail with a "Maximum update depth exceeded" error or an infinite loop. Older versions re-render too often. There are two fixes.
Wrap the selector in useShallow. It compares the array element by element. Here the elements are the same todo objects from the store, so the comparison succeeds.
import { useShallow } from 'zustand/react/shallow'
function OpenTodos() {
const open = useTodoStore(useShallow((state) => state.todos.filter((t) => !t.done)))
return (
<ul>
{open.map((t) => (
<li key={t.id}>{t.title}</li>
))}
</ul>
)
}Alternatively, select the stable source and derive in the component with useMemo.
import { useMemo } from 'react'
function OpenTodosMemo() {
const todos = useTodoStore((state) => state.todos)
const open = useMemo(() => todos.filter((t) => !t.done), [todos])
return <p>{open.length} open</p>
}Choosing an approach
| Situation | Approach |
|---|---|
| Result is a number, string or boolean | Compute in the selector |
| Result is a new array or object, and elements are stable | Selector with `useShallow` |
| Computation is expensive | Select the source, then `useMemo` |
| Many components need the same result | Write a shared selector function or custom hook |
Exercise
A component uses useTodoStore((state) => state.todos.map((t) => t.title)) and, in Zustand v5, throws a "Maximum update depth exceeded" error. Why does it happen, and what is the smallest fix?
Show answer
map returns a new array on every call, so the selector result never equals the previous result and the store keeps triggering renders. Wrap the selector in useShallow, which compares the array elements. Since the titles are strings, they compare equal when unchanged.