Use Immer when actions update nested objects and you want to write those updates without copying each level by hand. The examples below let you toggle todos and edit a person's details; the rendered values follow the store's updates.
Zustand still uses an immutable state model. The immer middleware converts draft-based updater functions into immutable updates before passing them to Zustand's set.
Start from the project in the React quick start. Keep its entry file, StrictMode wrapper, and stylesheet import; add the files below to that project.
1. Install Immer
Zustand includes the middleware, but you must install Immer as a direct dependency:
bashnpm install zustand immer
The command also installs Zustand if it is not already present. Import the middleware from zustand/middleware/immer, not from the immer package.
2. Update simple and nested state with drafts
Wrap the initializer passed to create in immer. Keep the extra parentheses in create<TodoStore>()(...) so TypeScript can type the store and infer the middleware.
Add this store. increment and decrement update a number; toggleTodo updates an object inside a record. Each updater changes its draft and returns nothing.
tsimport { create } from 'zustand'
import { immer } from 'zustand/middleware/immer'
type Todo = {
id: string
title: string
done: boolean
}
type TodoStore = {
count: number
todos: Record<string, Todo>
increment: (qty: number) => void
decrement: (qty: number) => void
toggleTodo: (todoId: string) => void
}
export const useTodoStore = create<TodoStore>()(
immer((set) => ({
count: 0,
todos: {
zustand: { id: 'zustand', title: 'Learn Zustand', done: false },
immer: { id: 'immer', title: 'Learn Immer', done: false },
},
increment: (qty) =>
set((state) => {
state.count += qty
}),
decrement: (qty) =>
set((state) => {
state.count -= qty
}),
toggleTodo: (todoId) =>
set((state) => {
const todo = state.todos[todoId]
if (todo) todo.done = !todo.done
}),
})),
)
immer takes a state creator and returns another state creator; it does not create a separate store. Its initializer receives set, get, and the store, like a regular Zustand initializer. Here, only set is needed.
3. Edit a nested person object without copying it
The same middleware works with createStore for a vanilla store. Add a setPerson action that accepts either a replacement person or a draft-editing callback. Type the callback with Immer's Draft and a void return: its job is to edit the draft, not return a person.
tsimport type { Draft } from 'immer'
import { createStore } from 'zustand/vanilla'
import { immer } from 'zustand/middleware/immer'
type Person = {
firstName: string
lastName: string
email: string
}
type PersonStore = {
person: Person
setPerson: (nextPerson: Person | ((person: Draft<Person>) => void)) => void
}
export const personStore = createStore<PersonStore>()(
immer((set) => ({
person: {
firstName: 'Barbara',
lastName: 'Hepworth',
email: 'bhepworth@sculpture.com',
},
setPerson: (nextPerson) =>
set((state) => {
if (typeof nextPerson === 'function') {
nextPerson(state.person)
} else {
state.person = nextPerson
}
}),
})),
)
Calling the callback inside set keeps the edit within Immer's recipe. A first-name edit leaves the last name and email in place. Passing a complete Person instead replaces only the nested person field.
4. Render the stores and invoke their actions
Use the todo store's bound hook and useStore for the vanilla person store. The person inputs invoke setPerson through getState(); the displayed values subscribe through useStore.
tsximport { useStore } from 'zustand'
import { personStore } from './immer-person-store'
import { useTodoStore } from './immer-todo-store'
export default function ImmerExamples() {
const count = useTodoStore((state) => state.count)
const todos = useTodoStore((state) => state.todos)
const increment = useTodoStore((state) => state.increment)
const decrement = useTodoStore((state) => state.decrement)
const toggleTodo = useTodoStore((state) => state.toggleTodo)
const person = useStore(personStore, (state) => state.person)
return (
<main style={{ minHeight: 400, display: 'grid', gap: 16, textAlign: 'left' }}>
<section>
<h1>Draft-based updates</h1>
<p aria-live="polite">Count: {count}</p>
<button type="button" onClick={() => increment(1)}>+1</button>
<button type="button" onClick={() => decrement(1)}>−1</button>
<ul>
{Object.values(todos).map((todo) => (
<li key={todo.id}>
<label>
<input
type="checkbox"
checked={todo.done}
onChange={() => toggleTodo(todo.id)}
/>
{todo.title}: {todo.done ? 'Done' : 'Not done'}
</label>
</li>
))}
</ul>
</section>
<section style={{ display: 'grid', gap: 8 }}>
<h2>Edit a person</h2>
<label>
First name
<input
value={person.firstName}
onChange={(event) => {
const value = event.currentTarget.value
personStore.getState().setPerson((draft) => {
draft.firstName = value
})
}}
/>
</label>
<label>
Last name
<input
value={person.lastName}
onChange={(event) => {
const value = event.currentTarget.value
personStore.getState().setPerson((draft) => {
draft.lastName = value
})
}}
/>
</label>
<label>
Email
<input
type="email"
value={person.email}
onChange={(event) => {
const value = event.currentTarget.value
personStore.getState().setPerson((draft) => {
draft.email = value
})
}}
/>
</label>
<p aria-live="polite">
{person.firstName} {person.lastName} ({person.email})
</p>
</section>
</main>
)
}
In the quick-start project's src/main.tsx, change the Counter import to import ImmerExamples from './ImmerExamples.tsx' and change <Counter /> to <ImmerExamples />; keep the rest of the quick start's mounting code unchanged.
tsximport { StrictMode } from 'react'
import { createRoot } from 'react-dom/client'
import './index.css'
import ImmerExamples from './ImmerExamples.tsx'
createRoot(document.getElementById('root')!).render(
<StrictMode><ImmerExamples /></StrictMode>,
)
bashnpm run build npm run dev
Open the URL printed by Vite. You see Count: 0, two unchecked todos, and Barbara Hepworth's details. Click +1 or −1 to change the count. Check a todo to change its label to Done. Edit any person field to update the summary beneath the inputs.
Immer produces the next immutable state from the recipe. Zustand compares that result with the current state and notifies subscriptions when they differ; the hooks connect those subscriptions to React. No manual refresh is needed.
Options that matter
The middleware has no configuration object. Pass it the initializer; the normal store update behavior still applies.
| Option | Type | Default | What it does |
|---|---|---|---|
| Initializer | State creator function | Required | Receives set, get, and the store; returns the initial data and actions. immer returns the wrapped creator. |
set's second argument, replace | boolean | false for object updates | false shallowly merges the produced update; true replaces the state. See Type stores and selectors for replacement typing and complete-state requirements. |
Keep class instances draftable
If your state contains class instances, mark those classes with [immerable] = true using immerable from the immer package. Without the marker, Immer can mutate the original class object instead of drafting it. Current and next state can then be equal, so Zustand skips subscription notifications.
Follow Immer's class-object rules and Immer's pitfalls. The examples here use plain objects. For updates without Immer, see Immutable state and merging.
Live demos
Try the basic Immer demo for draft-based actions, or the advanced Immer demo for a larger example.
Related
- Organize store actions covers where to put actions and how to read state within them.
- Split a store into slices covers middleware placement when you compose a larger store.
- Selectors and rendering explains how selected values determine React updates.
Was this page helpful?