Course contentsShow
← React
Lesson 1714 of 2,39641. State Management EcosystemFree lesson

Immer Middleware for Immutable Updates

Integrating immer() middleware to write mutable-looking update logic safely.

Immer Middleware for Immutable Updates

You'll learn how to use Zustand's immer middleware to write state updates that look mutable but remain safely immutable under the hood.

The Problem with Manual Immutability

When updating nested state in Zustand, you typically spread objects carefully to preserve immutability. This works, but becomes tedious with deeply nested structures:

set(state => ({
  user: {
    ...state.user,
    profile: {
      ...state.user.profile,
      settings: {
        ...state.user.profile.settings,
        darkMode: true
      }
    }
  }
}))

That's exhausting to write and error-prone.

What Immer Does

Immer lets you write code that appears to mutate state directly, but it secretly creates immutable copies behind the scenes. Think of it like editing a document with "track changes" on—you scribble all over it, but the original stays intact, and Immer produces a clean final copy.

Using Immer with Zustand

Wrap your store's set function with the immer middleware:

import { create } from 'zustand'
import { immer } from 'zustand/middleware/immer'

const useStore = create(
  immer((set) => ({
    user: { profile: { settings: { darkMode: false } } },
    toggleDarkMode: () => 
      set((state) => {
        // Direct "mutation" — Immer makes it safe
        state.user.profile.settings.darkMode = !state.user.profile.settings.darkMode
      })
  }))
)

Notice how you directly assign state.user.profile.settings.darkMode—no spreading! Immer intercepts this, tracks what changed, and produces a proper immutable update.

When to Use It

Reach for immer when your state has nested objects or arrays that require frequent updates. The more levels of nesting, the more valuable it becomes.

Key Takeaway: Zustand's immer middleware lets you write simple assignment-style updates while maintaining immutability, dramatically simplifying complex nested state logic without sacrificing safety.