Sub topic 16
Writing concise updates with Immer
This chapter assumes you know the spread operator, map and filter, useState, and the copy-based update patterns from earlier chapters. Here you will see how Immer lets you write the same updates with less code.
The problem Immer solves
Copying every object on the path to a changed value works, but it gets noisy as state gets deeper. A nested update needs one spread per level, and it is easy to forget one.
Immer is a library that lets you write code that looks like mutation. You edit a temporary copy called a draft. Immer then builds a new immutable state from your edits and leaves the original untouched. React still receives a new object, so the rules from earlier chapters still hold.
Using use-immer
The use-immer package provides useImmer, a drop-in replacement for useState. Install it first:
npm install immer use-immerThen call the updater with a function that edits the draft:
import { useImmer } from 'use-immer';
const [person, updatePerson] = useImmer({
name: 'Ada',
address: { city: 'London', country: 'UK' },
});
function handleCityChange(e) {
updatePerson((draft) => {
draft.address.city = e.target.value;
});
}Compare this with the spread version, which needed { ...person, address: { ...person.address, city } }. The Immer version names only the property that changes.
How it works
Immer records which parts of the draft you changed. It copies only those objects and the objects above them. Everything else is shared with the old state.
Arrays with Immer
Inside a draft, mutating array methods are allowed. You can use push, splice, and sort directly.
import { useImmer } from 'use-immer';
const [todos, updateTodos] = useImmer([
{ id: 0, title: 'Buy milk', done: false },
]);
function addTodo(title) {
updateTodos((draft) => {
draft.push({ id: draft.length, title, done: false });
});
}
function toggleTodo(id) {
updateTodos((draft) => {
const todo = draft.find((t) => t.id === id);
todo.done = !todo.done;
});
}Finding an item and editing it in place is easier than a map with a conditional copy.
Common errors
- Mutating outside the updater. Draft editing is safe only inside the function you pass to
updatePerson. Editingpersondirectly is still a bug. - Both returning and mutating. In the updater, either edit the draft or return a new value. Doing both throws an error.
- Forgetting that a draft is temporary. Do not save
draftsomewhere and use it after the updater finishes. Its contents are only valid during the call. - Using it where you do not need it. For flat state, a spread is shorter than adding a dependency.
Choosing between the approaches
| Situation | Better choice |
|---|---|
| Flat object with a few fields | Spread |
| One or two levels of nesting | Spread, or flatten the state |
| Deep nesting or many update handlers | Immer |
| Team unfamiliar with the library | Spread, until the cost is clear |
Exercise
Why does updatePerson((draft) => { draft.address.city = 'Paris'; }) not break React's rule against mutating state?
Show answer
The function edits a draft, which is a temporary copy. Immer uses the edits to create a new state object and leaves the original unchanged, so React receives a new reference and re-renders.
Exercise
Using useImmer, write a removeTodo(id) function for the todos array above.
Show answer
updateTodos((draft) => { const index = draft.findIndex((t) => t.id === id); if (index !== -1) draft.splice(index, 1); }); Splice is safe here because it mutates the draft, not the real state.