Sub topic 4
How Immer Lets Reducers "Mutate" State Safely
Prerequisites
This chapter assumes you have read the earlier chapters on the Redux model and createSlice. You should know that a reducer receives the current state and an action, and that Redux needs a new state object whenever something changes. You should also be comfortable with spread syntax and with the difference between mutating an object and copying it.
Why reducers must not mutate
Redux and React-Redux detect changes by comparing references with ===. useSelector re-runs your selector after each dispatch and re-renders only if the returned value is a different reference. If a reducer edits the existing object, the reference stays the same. The component does not re-render, memoized selectors return stale results, and DevTools cannot show a before and after.
The traditional fix is to copy every level of the path you change:
function todoToggled(state, action) {
return {
...state,
items: state.items.map((todo) =>
todo.id === action.payload
? { ...todo, completed: !todo.completed }
: todo
),
}
}This is correct but easy to get wrong. Forgetting one spread level introduces a mutation that no error message points to. Immer removes that class of bug.
What Immer does
Immer is a library bundled with Redux Toolkit. Its core function, produce(base, recipe), works in three steps:
- It wraps
basein a draft, which is a JavaScriptProxythat records every read and write. - It calls your recipe function with the draft. Inside the recipe you write ordinary mutating code.
- It looks at what the recipe changed and builds a new immutable object. The original
baseis never modified.
Redux Toolkit re-exports produce as createNextState, so you can try it without installing anything else:
import { createNextState } from '@reduxjs/toolkit'
const base = {
user: { name: 'Ana' },
todos: [
{ id: 1, completed: false },
{ id: 2, completed: false },
],
}
const next = createNextState(base, (draft) => {
draft.todos[0].completed = true
})
console.log(next === base) // false
console.log(base.todos[0].completed) // false: the original is untouched
console.log(next.todos[0].completed) // true
console.log(next.user === base.user) // true: unchanged branch is shared
console.log(next.todos[1] === base.todos[1]) // true: unchanged item is sharedThe last two lines show structural sharing. Immer copies only the objects on the path from the root to the changed value: the root, the todos array, and todos[0]. Everything else keeps its old reference. Components and selectors that read only the unchanged branches see identical references and skip work.
Where Immer runs in Redux Toolkit
You rarely call produce yourself. Redux Toolkit wraps it around the case reducers in createSlice, in createReducer, and in the extraReducers builder callbacks. A function passed to reducers therefore receives a draft as state:
import { createSlice } from '@reduxjs/toolkit'
const initialState = { items: [], filter: 'all' }
const todosSlice = createSlice({
name: 'todos',
initialState,
reducers: {
todoAdded(state, action) {
state.items.push(action.payload)
},
todoToggled(state, action) {
const todo = state.items.find((t) => t.id === action.payload)
if (todo) {
todo.completed = !todo.completed
}
},
filterChanged(state, action) {
state.filter = action.payload
},
todosReset() {
return initialState
},
},
})
export const { todoAdded, todoToggled, filterChanged, todosReset } =
todosSlice.actions
export default todosSlice.reducerPlain reducers that you write by hand and pass to combineReducers do not get this treatment. Immer only applies where Redux Toolkit applies it.
The rules inside a case reducer
Mutate the draft or return a value, never both
A reducer may either modify the draft and return nothing, or return a completely new value and leave the draft alone. Doing both throws an error in development:
// Throws: "An immer producer returned a new value *and* modified its draft."
todoToggled(state, action) {
const todo = state.items.find((t) => t.id === action.payload)
todo.completed = !todo.completed
return state.items // returns something different from the draft
}The todosReset reducer above shows the legitimate use of return: replacing the whole state. Returning is also the only way to set the entire state to undefined-like values, or to a different type, because assigning to the state parameter does nothing.
Assigning to `state` itself does not work
// Bug: this rebinds a local variable, so the store is not updated
todosReset(state) {
state = initialState
}state is only a parameter. Reassigning it changes the variable, not the draft. Either return the new value or assign to a property such as state.items = [].
Do not use the arrow shorthand carelessly
An arrow function with an expression body returns that expression. A reducer like (state) => state.items.push(x) returns the new array length, which Immer treats as a returned value. Use braces for any reducer that mutates.
Keep reducers pure
Immer changes how you write updates, not what a reducer is allowed to do. Reducers still must not call Math.random(), Date.now(), or fetch, and must not read from outside state. Generate ids and timestamps before dispatch, or in a prepare callback.
Inspecting drafts
A draft is a Proxy, so console.log(state) prints an opaque object. Use current to take a plain snapshot of the draft's present values:
import { createSlice, current } from '@reduxjs/toolkit'
const debugSlice = createSlice({
name: 'debug',
initialState: { count: 0 },
reducers: {
incremented(state) {
state.count += 1
console.log(current(state)) // { count: 1 }
},
},
})
export const { incremented } = debugSlice.actions
export default debugSlice.reduceroriginal(draft) returns the untouched base object instead. Use it when you need the value from before any edits in this reducer call. isDraft tells you whether a value is a draft.
Gotchas
- Drafts are revoked after the reducer ends. Do not keep a reference to
stateor a nested draft in a closure, a timeout, or a variable outside the reducer. Using it later throws a "revoked proxy" error. - State is frozen. Immer auto-freezes the result. Mutating store state outside a reducer, for example inside a component or a selector, throws a
TypeErrorin strict mode. This is useful because it exposes accidental mutations immediately. - Sorting in selectors needs a copy. Inside a reducer,
state.items.sort(...)is fine because it sorts the draft. In a selector the array is frozen, so use[...state.items].sort(...). - Only some types are draftable. Plain objects and arrays work.
MapandSetneedenableMapSet()fromimmer. Class instances are not drafted unless marked withimmerable. Redux state should be plain serializable data anyway. - No-op updates keep the old reference. If a recipe makes no real change, Immer returns the original object, so subscribers see no change. Assigning an equal primitive, such as
state.filter = 'all'when it is already'all', also counts as no change. - Proxies cost something. Drafts are created lazily, only for the branches you touch, so the overhead is small for typical reducers. For a bulk replacement of a large array, assigning the new array (
state.items = newItems) is cheaper than pushing items one by one.
Quick reference of common errors
| Symptom | Cause | Fix |
|---|---|---|
| Error about returning a new value and modifying the draft | Reducer both mutated and returned | Pick one style |
| State does not change after `state = x` | Rebinding the parameter | Return `x`, or assign to a property |
| Logged state prints as `Proxy` or looks empty | Logging a draft | Log `current(state)` |
| "Cannot perform 'get' on a proxy that has been revoked" | Draft used after the reducer finished | Copy plain values out with `current` or read what you need first |
| `TypeError: Cannot assign to read only property` | Mutating frozen state outside a reducer | Move the change into a reducer |
Exercise
A reducer contains todoRemoved(state, action) { state.items = state.items.filter((t) => t.id !== action.payload); return state.items }. What happens, and how do you fix it?
Show answer
It throws in development because the reducer modified the draft (state.items = ...) and also returned a different value (state.items). Remove the return so the reducer only mutates the draft. Alternatively, return a full replacement such as return { ...state, items: state.items.filter((t) => t.id !== action.payload) } without touching the draft.
Exercise
Using the base object from the createNextState example, you run createNextState(base, (draft) => { draft.user.name = 'Ana' }). Is the result === base? Why does this matter to useSelector?
Show answer
Yes. The name is already 'Ana', so the recipe makes no real change and Immer returns the original base reference. A selector that reads this state sees an identical reference and the component does not re-render, which avoids unnecessary work.