# Update state with Immer

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`](https://bench-zustand-61.atloria.app/p/bench-zustand-61-pSJCWrWW5Y/developer/zustand-middleware-immer#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](https://bench-zustand-61.atloria.app/p/bench-zustand-61-pSJCWrWW5Y/developer/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:

```bash
npm 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`](https://bench-zustand-61.atloria.app/p/bench-zustand-61-pSJCWrWW5Y/developer/zustand#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.

```ts title="src/immer-todo-store.ts"
import { 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`](https://bench-zustand-61.atloria.app/p/bench-zustand-61-pSJCWrWW5Y/developer/zustand#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`](https://immerjs.github.io/immer/typescript/) and a `void` return: its job is to edit the draft, not return a person.

```ts title="src/immer-person-store.ts"
import 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`](https://bench-zustand-61.atloria.app/p/bench-zustand-61-pSJCWrWW5Y/developer/zustand#usestore) for the vanilla person store. The person inputs invoke `setPerson` through `getState()`; the displayed values subscribe through `useStore`.

```tsx title="src/ImmerExamples.tsx"
import { 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](https://bench-zustand-61.atloria.app/p/bench-zustand-61-pSJCWrWW5Y/developer/react-quick-start#4-mount-the-counter) unchanged.

```tsx title="src/main.tsx"
import { 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>,
)
```

```bash
npm 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](https://bench-zustand-61.atloria.app/p/bench-zustand-61-pSJCWrWW5Y/developer/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](https://immerjs.github.io/immer/complex-objects) and [Immer's pitfalls](https://immerjs.github.io/immer/pitfalls). The examples here use plain objects. For updates without Immer, see [Immutable state and merging](https://bench-zustand-61.atloria.app/p/bench-zustand-61-pSJCWrWW5Y/developer/immutable-state-and-merging).

## Live demos

Try the [basic Immer demo](https://stackblitz.com/edit/vitejs-vite-3sgc4ejy) for draft-based actions, or the [advanced Immer demo](https://stackblitz.com/edit/vitejs-vite-jxxtuyj3) for a larger example.

## Related

- [Organize store actions](https://bench-zustand-61.atloria.app/p/bench-zustand-61-pSJCWrWW5Y/developer/organize-store-actions) covers where to put actions and how to read state within them.
- [Split a store into slices](https://bench-zustand-61.atloria.app/p/bench-zustand-61-pSJCWrWW5Y/developer/split-store-into-slices) covers middleware placement when you compose a larger store.
- [Selectors and rendering](https://bench-zustand-61.atloria.app/p/bench-zustand-61-pSJCWrWW5Y/developer/selectors-and-rendering) explains how selected values determine React updates.
