Sub topic 13
Nested updates with immer
This chapter assumes you can write a Zustand store with create, update it with set, and read the spread syntax for objects and arrays. It builds on the earlier chapters on updating state and on middleware.
The problem with nested state
Zustand's set merges only the top level of the object you give it. If your state is nested, you must copy every level on the path to the value you change. Here is a toggle on an item inside an array, written by hand:
set((state) => ({
todos: state.todos.map((t) =>
t.id === id ? { ...t, done: !t.done } : t,
),
}))This is correct, but it gets noisy as the nesting gets deeper. A missed spread silently drops fields or mutates shared state.
What immer does
immer is a separate library. It hands you a draft, which is a temporary copy of the state that you can change with ordinary assignments. When your function returns, immer works out what changed and builds a new immutable state. Untouched parts keep their old references, so selectors still skip re-renders for them.
Zustand ships an immer middleware that wires this into set. You must install the package first:
npm install immerUsing 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 toggle, state is a draft. The line todo.done = !todo.done looks like a mutation, but immer turns it into an immutable update.
Rules to remember
- Either mutate the draft or return a new object from the function. Do not do both in one call.
- With the middleware,
setstill accepts a plain partial object, so existing actions keep working. - Wrap only the state creator. When you combine middleware, place
immerinside the others, for exampledevtools(immer(...)). - Use immer when updates are deeply nested. For a flat store, plain
setis simpler and has no extra dependency.
Common mistakes
| Mistake | Result |
|---|---|
| Forgetting to install `immer` | The import of `zustand/middleware/immer` fails |
| Mutating `getState()` directly | The store is changed without notifying subscribers |
| Mutating and returning a value together | immer throws an error |
Exercise
In the toggle action above, why can you write todo.done = !todo.done without breaking Zustand's immutability rule?
Show answer
state is an immer draft, not the real state. immer records the assignment and produces a new immutable state object when the function returns. Only the changed branch gets new references, so subscribers are notified correctly.