Sub topic 16
Writing concise updates with Immer
This chapter assumes you know JavaScript objects, arrays, and the spread operator. It also assumes you can use useState and handle events in React. You should be comfortable with the copy patterns from earlier chapters: spreading objects, and using map, filter, and slice on arrays.
The problem Immer solves
Copying state by hand works, but it gets noisy as data gets deeper. Changing one city inside a nested object means copying every object on the path to it:
setPerson({
...person,
address: { ...person.address, city: e.target.value },
});Add one more level and the nesting grows again. It is also easy to forget one spread and mutate something by accident.
[Immer](https://immerjs.github.io/immer/) is a small library that lets you write code that looks like a mutation. It then turns that code into a correct, immutable update. You get short code and you still follow React's rule that state is read-only.
Installing and using useImmer
The use-immer package provides useImmer, a replacement for useState. Install it with your package manager:
npm install immer use-immeruseImmer returns the current state and an updater function. You can pass that function either a new value or a function that edits a 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;
});
}Inside the function, draft is a special stand-in for your state. You can assign to its properties as if it were a normal object. The original person is not touched.
How it works internally
Immer wraps your state in a JavaScript Proxy. A Proxy is an object that can watch every read and write made to the thing it wraps. The steps are:
- Immer hands your function a draft, which is a Proxy around the current state.
- Your function writes to the draft. Immer records each change instead of applying it to the original.
- When the function returns, Immer builds a new state. It copies only the objects along the changed paths.
- Every part you did not change keeps its old reference.
The last point matters for performance and for React. Unchanged branches keep the same identity, so React.memo and dependency checks can skip work for them.
Arrays become easy
With Immer, you may use the mutating array methods on a draft. push, splice, sort, and reverse are all safe there, because they change the draft and not your real state.
import { useImmer } from 'use-immer';
let nextId = 0;
export default function TodoList() {
const [todos, updateTodos] = useImmer([]);
function addTodo(title) {
updateTodos((draft) => {
draft.push({ id: nextId++, title, done: false });
});
}
function toggleTodo(id) {
updateTodos((draft) => {
const todo = draft.find((t) => t.id === id);
todo.done = !todo.done;
});
}
function removeTodo(id) {
updateTodos((draft) => {
const index = draft.findIndex((t) => t.id === id);
if (index !== -1) draft.splice(index, 1);
});
}
return (
<>
<button onClick={() => addTodo('Write notes')}>Add</button>
<ul>
{todos.map((t) => (
<li key={t.id}>
<label>
<input
type="checkbox"
checked={t.done}
onChange={() => toggleTodo(t.id)}
/>
{t.title}
</label>
<button onClick={() => removeTodo(t.id)}>Delete</button>
</li>
))}
</ul>
</>
);
}Compare toggleTodo with the map version from earlier. You find the item and change it. There is no copy to build.
Comparing the two styles
| Task | Plain `useState` | `useImmer` |
|---|---|---|
| Change a nested field | Spread each level | `draft.a.b = value` |
| Add to an array | `[...items, item]` | `draft.push(item)` |
| Remove from an array | `filter` | `splice` or `filter` |
| Update one item | `map` with a copied object | Find it and assign |
| Sort | Copy first, then `sort` | `draft.sort(...)` |
Rules and gotchas
Immer is simple, but it has rules. Breaking them gives confusing results.
Edit the draft or return a value, not both
Your function may either change the draft or return a new value. Doing both throws an error. Pick one style per call.
updateTodos((draft) => {
draft.push({ id: nextId++, title: 'New', done: false });
// Do not also return a new array here.
});An arrow function with a concise body returns its expression. This line returns the new length of the array from push, which causes the error:
// Wrong: returns the result of push
updateTodos((draft) => draft.push(item));
// Right: braces, no return
updateTodos((draft) => {
draft.push(item);
});Do not keep the draft after the function ends
A draft is only valid while your function runs. Immer revokes it afterward. Storing a draft in a variable outside the function, or using it in a timeout, fails with an error about a revoked proxy.
Do not mutate real state outside the function
Immer only protects you inside the updater. If you write person.address.city = 'Paris' directly, you are mutating real state and React will not re-render. Immer also freezes the state it produces in development, so this type of bug often throws an error instead of failing silently.
Class instances need extra setup
Immer works out of the box with plain objects, arrays, Map, and Set (the last two need enableMapSet()). Instances of your own classes are not drafted unless you mark them with immerable. Keep state as plain data where you can.
import { enableMapSet } from 'immer';
enableMapSet();When to use Immer
Immer is not required, and for many components it is more than you need.
| Situation | Suggestion |
|---|---|
| Flat object with a few fields | Plain spread is short enough |
| Array of simple items | `map`, `filter`, and spread work well |
| Deeply nested state you cannot flatten | Immer is a good fit |
| Many different kinds of updates in one component | Immer reduces mistakes |
| Team is unfamiliar with Proxies | Weigh the learning cost |
Flattening state, covered in the previous chapter, often removes the need for Immer. Try that first. Use Immer when the data really is nested, or when the copy code is hiding what the update does.
There is a cost. Immer adds a dependency to your bundle, and the Proxy approach has some overhead on very large states. For typical UI state this overhead is not noticeable.
Using produce without the hook
useImmer is a thin wrapper over produce from the immer package. You can call produce yourself with plain useState. This is handy when you already have useState and want Immer for one hard update:
import { useState } from 'react';
import { produce } from 'immer';
export default function Profile() {
const [person, setPerson] = useState({
name: 'Ada',
address: { city: 'London', country: 'UK' },
});
function handleCityChange(e) {
const city = e.target.value;
setPerson((prev) =>
produce(prev, (draft) => {
draft.address.city = city;
})
);
}
return <input value={person.address.city} onChange={handleCityChange} />;
}produce(prev, recipe) returns a new state and leaves prev unchanged. Note that the event value is read into city first. Reading e.target.value later is fine in current React, but copying it into a variable keeps the recipe free of event details.
Summary
Immer lets you write updates as direct edits to a draft, then produces a new immutable state with structural sharing. Use useImmer for convenience or produce with useState for one-off cases. Remember to edit or return, never both, and never hold on to a draft. Prefer flat state first, and reach for Immer when nesting makes plain copies hard to read.
Exercise
A teammate writes updateTodos((draft) => draft.push(newTodo)); and sees an error. Explain what causes it and how to fix it.
Show answer
The arrow function has a concise body, so it returns the value of draft.push(newTodo), which is the new array length. Immer then sees a function that both modified the draft and returned a different value, which is not allowed. Fix it by using braces and no return: updateTodos((draft) => { draft.push(newTodo); });.
Exercise
Using useImmer, write a function renameTodo(id, title) that changes the title of the todo with the given id in an array state called todos.
Show answer
updateTodos((draft) => { const todo = draft.find((t) => t.id === id); if (todo) todo.title = title; }); Wrap this in function renameTodo(id, title) { ... }. The find call returns a draft of the item, so assigning to title is recorded and Immer produces a new array with a new item object.