Sub topic 13
Nested updates with immer
This chapter assumes you know how create, selectors and set work in Zustand, and that you understand immutable updates (never changing an object in place, always building a new one). Here you will see why deeply nested state is awkward to update, and how the immer middleware fixes that.
The problem with nested state
Zustand's set merges only the top level of the object you give it. If you update a field that sits several levels deep, you must rebuild every object on the path to it. Here is a store with a nested user object:
import { create } from 'zustand'
interface ProfileState {
user: {
name: string
address: { city: string; zip: string }
}
setCity: (city: string) => void
}
export const useProfileStore = create<ProfileState>()((set) => ({
user: { name: 'Ada', address: { city: 'London', zip: 'N1' } },
setCity: (city) =>
set((state) => ({
user: {
...state.user,
address: { ...state.user.address, city },
},
})),
}))This works, but each extra level adds another spread. Forgetting one spread silently drops sibling fields. Updating an item inside an array is worse, because you need map and a spread for the matching item.
What immer does
immer is a small library that lets you write code that looks like mutation. It hands you a draft, a proxy copy of the state. You change the draft, and immer produces a new immutable object from your changes. The Zustand immer middleware wraps set so that it accepts such a function.
Install the immer package first, because Zustand does not bundle it:
npm install immerThen wrap your state creator with the middleware:
import { create } from 'zustand'
import { immer } from 'zustand/middleware/immer'
interface Todo {
id: number
title: string
done: boolean
}
interface TodoState {
todos: Todo[]
toggle: (id: number) => void
}
export const useTodoStore = create<TodoState>()(
immer((set) => ({
todos: [{ id: 1, title: 'Write tutorial', done: false }],
toggle: (id) =>
set((state) => {
const todo = state.todos.find((t) => t.id === id)
if (todo) todo.done = !todo.done
}),
})),
)Inside the function passed to set, state is the draft. The line todo.done = !todo.done looks like a mutation, but the real state is never touched. When the function returns, immer builds the next state and Zustand notifies subscribers as usual.
How the update works
immer records which parts of the draft you changed. It copies only the objects along the changed path and reuses everything else. This is called structural sharing.
Todo 2 is the same object in both trees. This matters for rendering. A selector that returns an untouched part of the state gets the same reference as before, so Zustand sees no change and the component does not re-render.
import { useTodoStore } from './todoStore'
function TodoItem({ id }: { id: number }) {
const todo = useTodoStore((state) => state.todos.find((t) => t.id === id))
if (!todo) return null
return <li>{todo.title}</li>
}When another todo is toggled, find returns the same object for this id, so TodoItem is skipped.
Two ways to call set
With the middleware installed, set accepts three forms:
| Form | Example | Result |
|---|---|---|
| Mutating function | `set((s) => { s.count += 1 })` | immer builds the next state from draft changes |
| Returning function | `set((s) => ({ count: s.count + 1 }))` | The returned object is merged, as in plain Zustand |
| Partial object | `set({ count: 0 })` | Merged, as in plain Zustand |
You can mix these freely in one store. Use the mutating form for nested changes and the simpler forms for flat ones.
Common errors
Mutating and returning in the same function
immer allows a function to either change the draft or return a new value. It does not allow both. This error is easy to trigger with arrow functions that have an expression body:
// Wrong: push returns the new length, so the function returns a number
// and also modified the draft. immer throws an error.
addTodo: (todo) => set((state) => state.todos.push(todo)),
// Right: a block body returns undefined
addTodo: (todo) =>
set((state) => {
state.todos.push(todo)
}),The same applies to set((s) => (s.count = 5)), which returns 5. Prefer a block body for every mutating function.
Using the draft after the function ends
A draft is only valid while the producer function runs. Do not store it in a variable outside, return it from an action, or use it after an await. If an async action needs a value from the state, read it with get() or copy plain values out first, then call set again for the update.
import { create } from 'zustand'
import { immer } from 'zustand/middleware/immer'
interface Item {
id: number
label: string
}
interface ItemState {
items: Item[]
rename: (id: number, label: string) => Promise<void>
}
export const useItemStore = create<ItemState>()(
immer((set) => ({
items: [{ id: 1, label: 'first' }],
rename: async (id, label) => {
await fetch(`/api/items/${id}`, { method: 'PATCH', body: JSON.stringify({ label }) })
set((state) => {
const item = state.items.find((i) => i.id === id)
if (item) item.label = label
})
},
})),
)Here the draft is created fresh inside the second set call, after the request finishes.
Maps, Sets and class instances
By default immer drafts only plain objects and arrays. To use Map or Set in state, call enableMapSet() from immer once at startup. Class instances are ignored unless the class is marked with [immerable] = true. For most stores, plain objects and arrays avoid both issues.
Frozen state
immer freezes the state it produces. If code outside set tries to change a state object directly, it throws an error in strict mode or silently fails otherwise. This catches accidental mutation, such as sorting state.todos in place inside a component. Copy first with [...todos].sort(...).
Composing with other middleware
Order matters because each middleware wraps the one inside it. A common arrangement puts immer innermost, so that devtools and persist see the final result:
import { create } from 'zustand'
import { devtools, persist } from 'zustand/middleware'
import { immer } from 'zustand/middleware/immer'
interface SettingsState {
prefs: { theme: string; notifications: { email: boolean; push: boolean } }
togglePush: () => void
}
export const useSettingsStore = create<SettingsState>()(
devtools(
persist(
immer((set) => ({
prefs: { theme: 'light', notifications: { email: true, push: false } },
togglePush: () =>
set((state) => {
state.prefs.notifications.push = !state.prefs.notifications.push
}),
})),
{ name: 'settings-storage' },
),
{ name: 'SettingsStore' },
),
)Keep the create<T>()(...) form so TypeScript can infer the middleware types.
When to use immer
Use it when your state has nested objects or arrays of objects that you update often. Skip it for flat stores, where set({ count: 1 }) is already short, and the extra dependency and proxy overhead buy nothing. immer costs some performance on very large updates, so measure before applying it to a hot path with thousands of changes per second.
Exercise
A teammate writes addTag: (tag) => set((state) => state.tags.push(tag)) in an immer store and gets an error at runtime. Why does it fail, and how do you fix it?
Show answer
The arrow function has an expression body, so it returns the result of push, which is the new array length. immer does not allow a function to both modify the draft and return a value. Fix it with a block body that returns nothing: set((state) => { state.tags.push(tag) }).
Exercise
After toggling one todo in an immer store, why does a TodoItem component for a different todo not re-render when it uses useTodoStore((s) => s.todos.find((t) => t.id === id))?
Show answer
immer uses structural sharing. It copies only the objects on the changed path and reuses the rest, so the untouched todo is the same object as before. The selector returns the same reference, Zustand sees no change, and the component is skipped.