Sub topic 12
Writing Immutable Updates with Immer
The earlier chapters built nested immutable updates by hand. You spread every object on the path to the change and leave every other branch shared. That works, but three or four levels down it turns into a wall of ... that is easy to get wrong. Immer is a small library that lets you write ordinary mutating code and still get back a new, structurally shared value.
This chapter assumes you can already write nested updates with spread, that you understand structural sharing and reference equality, and that you know what Object.freeze does. You also need Node.js 18 or later with ES modules, and Immer installed with npm install immer.
The core idea: mutate a draft, receive a new state
Immer's main function is produce. You pass it a base state and a recipe, which is a function that receives a draft. A draft is a stand-in for your state. You change the draft as though it were mutable. When the recipe finishes, Immer works out what changed and builds the next state from that.
import { produce } from 'immer';
const state = { todos: [{ id: 1, text: 'Write', done: false }] };
const next = produce(state, draft => {
draft.todos[0].done = true;
});
console.log(state.todos[0].done); // false
console.log(next.todos[0].done); // true
console.log(next === state); // falseThe original state is untouched. next is a new object, and only the objects along the path todos → todos[0] were copied.
Comparing with the hand-written version
Here is the same nested update from the chapter on nested data, written both ways:
import { produce } from 'immer';
const state = {
user: { name: 'Ada', address: { city: 'London' } },
settings: { theme: 'dark' }
};
// By hand
const manual = {
...state,
user: {
...state.user,
address: { ...state.user.address, city: 'Paris' }
}
};
// With Immer
const viaImmer = produce(state, draft => {
draft.user.address.city = 'Paris';
});
console.log(manual.user.address.city); // 'Paris'
console.log(viaImmer.user.address.city); // 'Paris'
console.log(viaImmer.settings === state.settings); // true, shared branch
console.log(viaImmer.user === state.user); // false, copied pathBoth results have the same shape and the same sharing. The Immer version states the intent in one line.
How it works internally
A draft is a JavaScript Proxy wrapped around your original object. Immer creates child proxies lazily, the first time you read a nested object through the draft. Each proxy tracks two things: the original object and, once you write to it, a shallow copy that holds your changes.
When you assign to a draft property, Immer:
- Makes a shallow copy of that node if it has not already done so.
- Writes the new value into the copy.
- Marks the node and every ancestor as modified.
When the recipe returns, Immer finalizes the tree. Modified nodes become their copies. Unmodified nodes are replaced by their original objects, which is where structural sharing comes from. If nothing was modified, produce returns the original base state itself.
That "nothing changed" rule matters for change detection. A no-op update keeps the old reference, so prev === next checks stay cheap and correct:
import { produce } from 'immer';
const state = { count: 0 };
const same = produce(state, draft => {
if (draft.count > 10) draft.count = 0;
});
console.log(same === state); // true, nothing was writtenImmer also notices assignments that write back the value that is already there, such as draft.count = draft.count, and does not treat them as changes.
Automatic freezing
By default Immer deep-freezes the objects it produces. That includes new values you put into the tree, as well as copied nodes. Code that later tries to mutate the result fails the way it would on any frozen object: it throws a TypeError in strict mode and is silently ignored otherwise.
import { produce } from 'immer';
const next = produce({ list: [] }, draft => {
draft.list.push({ id: 1 });
});
console.log(Object.isFrozen(next)); // true
console.log(Object.isFrozen(next.list[0])); // trueES modules always run in strict mode, so next.list[0].id = 2 in this file would throw. You can turn freezing off with setAutoFreeze(false) when profiling shows it costs too much on very large trees. You then lose the guard against accidental mutation.
Two ways to write a recipe
Mutate the draft and return nothing
This is the usual style. The recipe returns undefined, and Immer builds the result from the draft.
Return a new value
You can also return a replacement value from the recipe. This is handy when you swap out the whole state, or when filter reads better than a loop with splice:
import { produce } from 'immer';
const todos = [
{ id: 1, done: true },
{ id: 2, done: false }
];
const pending = produce(todos, draft => draft.filter(t => !t.done));
console.log(pending); // [ { id: 2, done: false } ]The one rule is that you must not do both. If a recipe modifies the draft and returns a different value, Immer throws an error.
The arrow-function trap
This rule catches people who write concise arrow functions:
import { produce } from 'immer';
const state = { count: 0 };
try {
produce(state, draft => draft.count++); // returns 0 after modifying
} catch (err) {
console.log(err.message); // Immer complains about returning a new value and modifying the draft
}
const ok1 = produce(state, draft => { draft.count++; });
const ok2 = produce(state, draft => void draft.count++);
console.log(ok1.count, ok2.count); // 1 1draft.count++ evaluates to the old number, so the arrow function returns it. Wrap the body in braces or prefix it with void.
To make the result literally undefined, return Immer's nothing token. A plain return undefined means "use the draft".
Curried producers
If you call produce with only a recipe, it returns a reusable function that takes the state first and then any extra arguments. This style fits reducers and event handlers well:
import { produce } from 'immer';
const toggleTodo = produce((draft, id) => {
const todo = draft.find(t => t.id === id);
if (todo) todo.done = !todo.done;
});
const todos = [
{ id: 1, done: false },
{ id: 2, done: false }
];
const next = toggleTodo(todos, 2);
console.log(next[1].done); // true
console.log(next[0] === todos[0]); // true, untouched item sharedRedux Toolkit's createSlice runs your case reducers through Immer this way. That is why mutating state inside a slice reducer is safe there.
Gotchas and failure modes
Drafts are revoked after the recipe ends
Immer revokes each proxy once produce finishes. If a draft escapes, for example through a callback that runs later or an await inside the recipe, any later access throws a TypeError about a revoked proxy. Keep recipes synchronous. If you need async work, do it first and then call produce with the results. Immer has limited support for async recipes, but the synchronous style is far easier to reason about.
Logging a draft is confusing
console.log(draft) prints a Proxy. Use current(draft) to get a plain snapshot of the draft's present state, or original(draft) to see the value it started from.
import { produce, current, original } from 'immer';
produce({ n: 1 }, draft => {
draft.n = 2;
console.log(current(draft)); // { n: 2 }
console.log(original(draft)); // { n: 1 }
});Reassigning the draft does nothing
draft = { ...newStuff } only rebinds the local parameter. Immer never sees it. Either mutate properties on the draft or return the new value.
Only some types become drafts
| Type | Drafted? | Notes |
|---|---|---|
| Plain objects and arrays | Yes | Default behavior |
| `Map` and `Set` | Yes, after `enableMapSet()` | Call it once at app startup |
| Class instances | Only with `[immerable] = true` | Otherwise treated as opaque values |
| `Date`, typed arrays, DOM nodes | No | Replace them, do not mutate them in place |
For example, calling draft.created.setFullYear(2030) on a Date changes the original Date object, because Immer never wrapped it. Assign a new Date instead.
Overhead on hot paths
Proxies, finalization, and freezing cost more than a hand-written spread. For typical UI state the difference rarely matters. In tight loops that update thousands of items, run one produce around the whole batch rather than one per item, or write the update by hand.
Patches
Immer can also report what changed. Call enablePatches() once, then produceWithPatches returns the next state, a list of patches, and the inverse patches. These are useful for undo/redo or for sending small diffs over the network.
import { enablePatches, produceWithPatches, applyPatches } from 'immer';
enablePatches();
const base = { user: { name: 'Ada' } };
const [next, patches, inverse] = produceWithPatches(base, draft => {
draft.user.name = 'Grace';
});
console.log(patches); // [ { op: 'replace', path: [ 'user', 'name' ], value: 'Grace' } ]
const undone = applyPatches(next, inverse);
console.log(undone.user.name); // 'Ada'When to reach for Immer
Use Immer when updates are deeply nested, when several fields change in one update, or when a team keeps writing spread-heavy code with mistakes in it. A one-level update is clearer with plain spread, so keep that. Keep in mind that Immer still produces ordinary objects and arrays. The values are not a new data type, so the rest of your code, including === change detection, keeps working unchanged.
Exercise
What does each call log, and why? (a) const s = { a: { b: 1 } }; const r = produce(s, d => { d.a.b = 1; }); console.log(r === s); (b) const r2 = produce(s, d => { d.a.b = 2; }); console.log(r2.a === s.a);
Show answer
(a) logs true. Writing the same value back is not a change, so Immer returns the base state itself. (b) logs false. a lies on the modified path, so Immer copied it. Any sibling branches would be shared.
Exercise
This code throws. Explain the cause and give two fixes: const add = produce((draft, item) => draft.items.push(item));
Show answer
push returns the new array length, so the arrow function returns a number after it has modified the draft. Immer forbids modifying the draft and also returning a different value. Fix it with braces, (draft, item) => { draft.items.push(item); }, or with void, (draft, item) => void draft.items.push(item).
Exercise
A recipe does draft.meta.updatedAt.setTime(Date.now()), where updatedAt is a Date. What goes wrong, and what should it do instead?
Show answer
Immer does not draft Date objects, so setTime mutates the original Date that the previous state shares. The old state changes as well, and no copy is recorded. Assign a new value instead: draft.meta.updatedAt = new Date().