Sub topic 17
Common pitfalls and when not to use Zustand
This chapter assumes you can build a store with create, read it with selectors, and update it with set. It covers the mistakes that cause extra renders, stale or lost state, and shared-state bugs. It ends with criteria for deciding when Zustand is the wrong tool.
Pitfall 1: Selecting the whole store
Calling the hook with no selector returns the entire state object. The component then re-renders on every change to any field.
import { useCounterStore } from './counterStore'
function Controls() {
// Re-renders whenever any field in the store changes
const { increment } = useCounterStore()
return <button onClick={increment}>Add one</button>
}Select only what the component uses:
import { useCounterStore } from './counterStore'
function Controls() {
const increment = useCounterStore((state) => state.increment)
return <button onClick={increment}>Add one</button>
}Action functions are created once and never change, so selecting one never triggers a re-render.
Pitfall 2: Selectors that return new references
A selector runs after every store update. React compares its result to the previous result with Object.is. If the selector builds a new object or array each time, the comparison always fails.
import { useUserStore } from './userStore'
function Profile() {
// Returns a new object on every call
const { name, email } = useUserStore((state) => ({
name: state.name,
email: state.email,
}))
return <p>{name} ({email})</p>
}In Zustand v5, this pattern can fail with a "Maximum update depth exceeded" error. In v4, it causes an extra render on every store change. Two fixes work:
- Select each primitive value with its own hook call.
- Wrap the selector in
useShallow, which compares the top-level fields of the result.
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>
}The same problem appears with .filter(), .map() and .sort() inside a selector. Each returns a new array. Wrap these in useShallow too, or compute the result with useMemo in the component, as the next section shows.
import { useMemo } from 'react'
import { useTodoStore } from './todoStore'
function OpenTodos() {
const todos = useTodoStore((state) => state.todos)
const open = useMemo(() => todos.filter((t) => !t.done), [todos])
return <p>{open.length} open</p>
}Pitfall 3: Storing derived values
If a value can be computed from other state, do not store it. A stored copy must be updated in every action that changes its sources. Missing one action leaves the two out of sync.
import { create } from 'zustand'
interface CartState {
prices: number[]
total: number // risky: must be kept in sync by hand
}
interface BetterCartState {
prices: number[]
}
export const useCartStore = create<BetterCartState>()(() => ({
prices: [10, 20],
}))
// Compute on read, in a component or a plain function
export const selectTotal = (state: BetterCartState) =>
state.prices.reduce((sum, p) => sum + p, 0)A selector that returns a number is safe, because numbers compare by value. Use useCartStore(selectTotal).
Pitfall 4: Mutating state
Zustand detects changes by reference. If you mutate an array or object in place and call set with the same reference, subscribers may see no change.
import { create } from 'zustand'
interface ListState {
items: string[]
addBad: (item: string) => void
addGood: (item: string) => void
}
export const useListStore = create<ListState>()((set) => ({
items: [],
// Wrong: same array reference, so selectors on items see no change
addBad: (item) =>
set((state) => {
state.items.push(item)
return { items: state.items }
}),
// Right: new array
addGood: (item) => set((state) => ({ items: [...state.items, item] })),
}))If nested updates become tedious, use the immer middleware instead of spreading by hand.
Pitfall 5: Expecting `set` to merge deeply
set merges only the top level. Returning a nested object replaces that whole branch.
import { create } from 'zustand'
interface SettingsState {
settings: { theme: string; fontSize: number }
setTheme: (theme: string) => void
}
export const useSettingsStore = create<SettingsState>()((set) => ({
settings: { theme: 'light', fontSize: 14 },
// Wrong: this removes fontSize
// setTheme: (theme) => set({ settings: { theme } }),
setTheme: (theme) =>
set((state) => ({ settings: { ...state.settings, theme } })),
}))The second argument to set is a replace flag. set(newState, true) replaces the whole state, including your actions, unless newState contains them. Use it for resets, as in the testing chapter, and pass a complete state object.
Pitfall 6: Creating stores in the wrong place
create should be called once, at module level. Calling it inside a component makes a new store on every render, and the state resets each time.
A module-level store is also a singleton. In server rendering (for example Next.js), the module is shared across requests, so one user's data can leak into another user's response. For server-rendered apps, use createStore with a context provider so each request gets its own instance.
Pitfall 7: Persist and hydration surprises
persist reads from localStorage when the store is created. On the server there is no localStorage, and the client's first render may differ from the server's HTML. This causes hydration warnings. Other persist issues:
- Changing the shape of persisted state breaks returning users. Set a
versionand amigratefunction. - Persisting everything saves loading flags and errors. Use
partializeto choose fields. - Functions cannot be serialized, so actions are never written to storage.
import { create } from 'zustand'
import { persist } from 'zustand/middleware'
interface PrefsState {
theme: 'light' | 'dark'
loading: boolean
setTheme: (theme: 'light' | 'dark') => void
}
export const usePrefsStore = create<PrefsState>()(
persist(
(set) => ({
theme: 'light',
loading: false,
setTheme: (theme) => set({ theme }),
}),
{
name: 'prefs',
version: 1,
partialize: (state) => ({ theme: state.theme }),
},
),
)Pitfall 8: Using the store for server data
Zustand does not fetch, cache, deduplicate or revalidate. The async action from earlier works for one simple request. For many endpoints, you would rewrite caching, retries, stale data handling and request cancellation by hand. A server-state library such as TanStack Query or SWR handles these. A common split is to use a server-state library for data from the API and Zustand for client-only state such as open panels, selected rows and draft input.
When Zustand is the wrong tool
| Situation | Better choice |
|---|---|
| State used by one component or a small subtree | `useState` or `useReducer` |
| Data from an API with caching needs | TanStack Query or SWR |
| Value that rarely changes (theme, locale) passed deep | React context |
| State that belongs in the URL (filters, page) | Router search params |
| Large team that wants strict event logging and conventions | Redux Toolkit |
| Fine-grained, graph-like dependent values | An atom library such as Jotai |
Checklist before shipping a store
- Every
useStorecall passes a selector. - Selectors that build objects or arrays use
useShallow, or are replaced by per-value selectors. - Derived values are computed on read, not stored.
- Updates return new references, or use
immer. - Nested updates spread the nested object.
- Stores are created at module level, or per request in server-rendered apps.
- Persisted state has a
name,versionandpartialize.
Exercise
A component calls const { items, total } = useCartStore((s) => ({ items: s.items, total: s.items.length })). Name two problems and give one fix for each.
Show answer
First, the selector returns a new object on every call, so the component re-renders on every store update (and v5 may throw "Maximum update depth exceeded"). Wrap the selector in useShallow, or select items and the length separately. Second, total is derived from items, so it should not be a stored field. Compute it on read with items.length, or select (s) => s.items.length, which returns a number and compares by value.
Exercise
Your store has settings: { theme, fontSize }. An action runs set({ settings: { theme: 'dark' } }) and fontSize becomes undefined. Why, and how do you fix it?
Show answer
set merges only top-level keys, so the settings value is replaced as a whole. Spread the existing nested object: set((state) => ({ settings: { ...state.settings, theme: 'dark' } })), or use the immer middleware.
Exercise
Your Next.js app uses a module-level Zustand store, and users occasionally see another user's data in the server-rendered HTML. What is the cause and the fix?
Show answer
The module-level store is a singleton shared by all requests on the server, so state set during one request is visible to the next. Create the store per request with createStore inside a context provider, and read it with useStore.