Sub topic 12
Writing Immutable Updates with Immer
This chapter assumes you already know how to write nested immutable updates with spread syntax, and that you understand structural sharing and change detection with reference equality. The examples use ES modules and need the immer package (npm install immer).
Why Immer Exists
Spread-based updates are correct, but they get noisy as nesting grows. To change one field three levels deep, you copy every object along the path by hand. If you miss one level, you end up mutating shared state without noticing.
Immer lets you write ordinary mutating code against a temporary draft. When your function finishes, Immer builds a new immutable state. It copies only the objects you touched and shares every other branch with the original.
How produce Works
produce(base, recipe) takes the current state and a recipe function. The recipe receives a draft, which is a Proxy wrapping the base state. Immer records each read and write on the draft. When the recipe returns, Immer turns those writes into new objects along the changed paths.
import { produce } from 'immer';
const state = {
user: { name: 'Ada', address: { city: 'London' } },
settings: { theme: 'dark' },
todos: [{ id: 1, text: 'Write', done: false }]
};
const next = produce(state, draft => {
draft.user.address.city = 'Paris';
draft.todos.push({ id: 2, text: 'Review', done: false });
});
console.log(state.user.address.city); // 'London'
console.log(next.user.address.city); // 'Paris'
console.log(next.settings === state.settings); // true, untouched branch is shared
console.log(next.todos[0] === state.todos[0]); // true, unchanged item is reused
console.log(Object.isFrozen(next)); // true, Immer auto-freezes results
const same = produce(state, draft => {
draft.settings.theme = 'dark'; // assigns the value it already has
});
console.log(same === state); // true, no real change means the same referenceThe last check matters for change detection. If a recipe makes no real changes, produce returns the original reference, so a === comparison correctly reports that nothing changed.
Curried Producers
If you pass only a recipe, produce returns a reusable updater function. That shape fits reducers and state setters well.
import { produce } from 'immer';
const toggleTodo = produce((draft, id) => {
const todo = draft.todos.find(t => t.id === id);
if (todo) todo.done = !todo.done;
});
const state = { todos: [{ id: 1, text: 'Write', done: false }] };
const next = toggleTodo(state, 1);
console.log(next.todos[0].done); // true
console.log(state.todos[0].done); // falseCommon Errors
| Mistake | What happens | Fix |
|---|---|---|
| Mutating the draft and also returning a new object | Immer throws an error | Do one or the other: mutate the draft, or return a replacement value |
| `draft => draft.count = 1` without braces | The arrow function returns `1`, which Immer reads as a replacement for the draft | Wrap the body in braces: `draft => { draft.count = 1; }` |
| Using a `Map` or `Set` in state | Immer throws until Map and Set support is turned on | Call `enableMapSet()` once at startup |
| Calling `console.log(draft)` | Prints a Proxy, which is hard to read | Use `current(draft)` from `immer` to get a plain snapshot |
| Mutating the result later | Fails, because results are frozen (throws in strict mode) | Run another `produce` call |
| Keeping a draft after the recipe ends | The Proxy is revoked, so using it throws | Use drafts only inside the recipe |
Exercise
Rewrite this spread-based update with Immer: const next = { ...state, user: { ...state.user, address: { ...state.user.address, city: 'Paris' } } };. After your change, will next.settings === state.settings be true?
Show answer
const next = produce(state, draft => { draft.user.address.city = 'Paris'; });. Yes. Immer copies only user and address, the objects on the changed path, and shares settings with the original state.
Exercise
Why does produce(state, draft => draft.done = true) throw, and how do you fix it?
Show answer
An arrow function with no braces returns the value of the assignment, which is true. Immer sees that the recipe both changed the draft and returned a new value, so it throws. Add braces so the recipe returns undefined: draft => { draft.done = true; }.