Sub topic 6
Derived state without storing it
Derived state is a value you can calculate from other state. Examples are the total of a cart, the number of unfinished todos, or the list of items that match a search. This chapter shows how to compute these values in selectors instead of saving them in the store.
It assumes you can already create a store, write a selector, and update state with set. It also assumes you know that Zustand compares a selector's result with Object.is to decide whether to re-render.
Why not store derived values
Suppose a cart store keeps items and also a total field. Every action that changes items must also update total. If one action forgets, the two disagree, and the UI shows a wrong number.
import { create } from 'zustand'
interface BadCartState {
items: { id: number; price: number; quantity: number }[]
total: number
addItem: (item: { id: number; price: number; quantity: number }) => void
}
// Anti-pattern: total duplicates information already held in items.
export const useBadCartStore = create<BadCartState>()((set) => ({
items: [],
total: 0,
addItem: (item) =>
set((state) => ({
items: [...state.items, item],
total: state.total + item.price * item.quantity,
})),
}))This works until you add removeItem, setQuantity, or a discount. Each one needs its own total arithmetic. A store should hold the smallest set of facts, and everything else should be calculated from them.
Computing derived values in a selector
A selector is a function from state to a value, so it can do the calculation. The component re-renders only when the result changes.
import { create } from 'zustand'
interface CartItem {
id: number
name: string
price: number
quantity: number
}
interface CartState {
items: CartItem[]
addItem: (item: CartItem) => void
setQuantity: (id: number, quantity: number) => void
}
export const useCartStore = create<CartState>()((set) => ({
items: [],
addItem: (item) => set((state) => ({ items: [...state.items, item] })),
setQuantity: (id, quantity) =>
set((state) => ({
items: state.items.map((i) => (i.id === id ? { ...i, quantity } : i)),
})),
}))
export const selectTotal = (state: CartState) =>
state.items.reduce((sum, i) => sum + i.price * i.quantity, 0)
export const selectItemCount = (state: CartState) =>
state.items.reduce((sum, i) => sum + i.quantity, 0)
export function CartSummary() {
const total = useCartStore(selectTotal)
const count = useCartStore(selectItemCount)
return (
<p>
{count} items, ${total.toFixed(2)}
</p>
)
}Three points about this code:
totalandcountare numbers, soObject.iscompares them by value. Changing an item'snameproduces the same total, andCartSummarydoes not re-render.- The selectors are defined outside any component. They have a stable identity and can be reused and tested without React.
- No action does any total arithmetic, so no action can get it wrong.
Derived values that are arrays or objects
Numbers and strings are easy. A selector that filters or maps returns a new array on every call, and Object.is sees a different array each time.
// Problem: filter creates a new array on every call.
const open = useTodoStore((state) => state.todos.filter((t) => !t.done))In Zustand v4 this causes a re-render after every store update. In Zustand v5 it is worse. The hook is built on React's useSyncExternalStore, which needs a stable result between calls. A selector that returns a fresh reference each time can fail with a "Maximum update depth exceeded" error.
There are two fixes.
Fix 1: useShallow
useShallow compares the result element by element. If the new array holds the same items as the previous one, the old reference is kept.
import { create } from 'zustand'
import { useShallow } from 'zustand/react/shallow'
interface Todo {
id: number
title: string
done: boolean
}
interface TodoState {
todos: Todo[]
toggle: (id: number) => void
}
export 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)),
})),
}))
export 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>
)
}This relies on immutable updates. toggle copies only the todo it changes, so unchanged todos keep their references and the shallow comparison succeeds. If you mutated todos in place, the comparison would miss the change.
Fix 2: select raw state and derive with useMemo
Select the stable input, then compute in the component.
import { useMemo, useState } from 'react'
import { useTodoStore } from './todoStore'
export function SearchableTodos() {
const todos = useTodoStore((state) => state.todos)
const [query, setQuery] = useState('')
const matches = useMemo(
() => todos.filter((t) => t.title.toLowerCase().includes(query.toLowerCase())),
[todos, query],
)
return (
<>
<input value={query} onChange={(e) => setQuery(e.target.value)} />
<p>{matches.length} matches</p>
</>
)
}This approach fits when the calculation depends on something outside the store, such as local component state. A selector cannot see query. It also suits expensive calculations, as the next section explains.
Cost: selectors run often
Zustand runs every mounted selector on every set call. React may also run a selector again during a render. A selector that sorts 10,000 rows runs that sort for every component that uses it, on every store change, even unrelated ones.
| Situation | Approach |
|---|---|
| Cheap result that is a number, string, or boolean | Selector returning the value |
| Cheap list built with `filter` or `map` | Selector wrapped in `useShallow` |
| Depends on props or local state | Select raw state, derive with `useMemo` |
| Expensive calculation | Select raw state, derive with `useMemo` |
| Needed inside an action | Call `get()` and calculate there |
Derived values inside actions
An action does not need a hook. It can call get() to read the current state and calculate from it.
import { create } from 'zustand'
interface CheckoutState {
items: { id: number; price: number; quantity: number }[]
lastOrderTotal: number | null
checkout: () => void
}
export const useCheckoutStore = create<CheckoutState>()((set, get) => ({
items: [{ id: 1, price: 4.5, quantity: 2 }],
lastOrderTotal: null,
checkout: () => {
const total = get().items.reduce((sum, i) => sum + i.price * i.quantity, 0)
set({ items: [], lastOrderTotal: total })
},
}))Here lastOrderTotal is stored on purpose. It is a record of a past event, not a value that follows the current items. If you clear the cart, the old order's total must not change. The question to ask is whether the value should always match other state, or whether it is a snapshot.
Naming and sharing selectors
Exporting selectors next to the store gives you one definition of each derived value. Components, tests, and non-React code can all use it.
import { useCartStore, selectTotal } from './cartStore'
useCartStore.getState().addItem({ id: 1, name: 'Pen', price: 2, quantity: 3 })
console.log(selectTotal(useCartStore.getState())) // 6Because a selector is a plain function of state, you can test it by passing a hand-built state object, with no rendering.
Exercise
A component calls useStore((s) => s.users.map((u) => u.name)) and re-renders after every store update, even when no user changes. Give two ways to fix it, and say which one you would choose if the component also filters the names by a search box held in useState.
Show answer
Fix 1: wrap the selector in useShallow, so the new array is compared element by element and the old reference is kept when the names are equal. Fix 2: select s.users and compute the names with useMemo. With the search box in useState, choose useMemo, because the selector cannot read local component state. Compute the filtered names from the selected users and the query inside the memo.
Exercise
A store holds items and a total field that every action updates by hand. Describe how to remove the duplication, and name one case where keeping a stored total is correct.
Show answer
Delete total from the store and export a selector such as (state) => state.items.reduce((sum, i) => sum + i.price * i.quantity, 0). Components read it with useStore(selectTotal), and actions that need it call get() and run the same reduce. A stored total is correct when it is a snapshot of a past event, for example the total of the last completed order, which must not change when the cart changes later.