Sub topic 4
How Immer lets reducers "mutate" state safely
This chapter assumes you know what a slice is (see the previous chapter) and that Redux state must be updated immutably. Immutable means you build a new object instead of changing the old one.
The problem: immutable updates by hand
Redux needs a new object for every change, because React-Redux detects changes by comparing references. Updating a nested value with plain JavaScript takes a lot of spreading:
function toggleTodo(state, id) {
return {
...state,
items: state.items.map((todo) =>
todo.id === id ? { ...todo, completed: !todo.completed } : todo
),
}
}Leaving out one spread silently mutates the old state. Immer, which Redux Toolkit includes, removes this risk.
How Immer works
Immer does not let you change the real state. When a reducer in createSlice runs, Immer wraps the current state in a draft, a proxy object that records every write. Your code changes the draft. Afterward, Immer builds a new immutable state that applies those recorded changes.
Immer copies only the objects along the path you changed. Untouched parts keep their old references, so selectors and useSelector comparisons still work efficiently.
Two ways to write a reducer
Inside a case reducer you can either mutate the draft or return a new value.
import { createSlice } from '@reduxjs/toolkit'
const todosSlice = createSlice({
name: 'todos',
initialState: {
items: [{ id: 1, text: 'Learn Immer', completed: false }],
filter: 'all',
},
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
}
},
todosCleared() {
return { items: [], filter: 'all' }
},
},
})
export const { todoAdded, todoToggled, todosCleared } = todosSlice.actions
export default todosSlice.reducerUse mutation for edits. Use return to replace the whole state, as todosCleared does.
Common errors
| Mistake | What happens | Fix |
|---|---|---|
| `state = { ...state, filter: 'done' }` | Only reassigns the local variable. The state does not change. | Write `state.filter = 'done'`, or return the new object. |
| Mutating the draft and also returning a new object | Immer throws an error. | Do one or the other. |
| Mutating state outside a `createSlice` or `createReducer` reducer | Real mutation, which can cause missed re-renders. | Do those writes only inside reducers. |
| `console.log(state)` in a reducer | Prints a Proxy that is hard to read. | Log `current(state)`. |
import { current } from '@reduxjs/toolkit'
// Inside a reducer:
console.log(current(state))Reducers must stay pure. Do not call Math.random(), Date.now() or an API inside them. Generate such values before dispatching and pass them in the action.
Exercise
A reducer runs state.items.push(action.payload) and then ends with return { ...state }. What happens, and how do you fix it?
Show answer
Immer throws an error, because the reducer both modified the draft and returned a different object. Remove the return statement and keep the push.