Skip to content
Tutorials Center
My learning

Topics

Lesson 30 of 41 ยท Patterns and Performance

Immutable Updates and Immer

Why Redux state must never be mutated, how to write correct immutable updates by hand, how Immer drafts make mutating syntax safe in createSlice, and the pitfalls to avoid.

Redux depends on one rule: never mutate state. A reducer must return a new object when something changed and the same object when nothing did. React-Redux, selectors, memoization, DevTools and time travel all detect change with a cheap reference check (===). If you mutate in place, the reference stays the same, nothing notices, and the screen shows stale data.

Writing immutable updates by hand is correct but verbose for nested state. Redux Toolkit solves this with Immer: inside createSlice you write code that looks like mutation, and Immer turns it into an immutable update. This lesson covers both, so you understand what Immer saves you from.

The mutation bug

JS A mutating reducer fails silently

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The bad reducer changed the data, but no subscriber was notified. A React component would not re-render. Mutation bugs are quiet like this, which is why Redux Toolkit freezes state in development and throws when you try to mutate it outside of Immer.

Immutable updates by hand

The recipe: copy every level on the path to the change, and reuse everything else.

JavaScript
// state: { user: { name, address: { city, zip } }, todos: [...] }
return {
  ...state,                                   // copy the root
  user: {
    ...state.user,                            // copy user
    address: { ...state.user.address, city: 'Oslo' },  // copy address, change one field
  },
};

Array operations that are safe (they return new arrays) versus unsafe (they mutate):

Task Safe Mutates (avoid)
Add [...a, x], a.concat(x) a.push(x)
Remove a.filter(i => i.id !== id) a.splice(i, 1)
Replace a.map(i => i.id === id ? {...i, done: true} : i) a[i] = x
Sort [...a].sort(fn), a.toSorted(fn) a.sort(fn)
Reverse [...a].reverse(), a.toReversed() a.reverse()

structuredClone(state) copies everything, but it also gives every object a new reference, which defeats the purpose: unchanged parts should keep their identity so components that depend on them skip re-rendering.

How Immer works

Immer gives your function a draft: a proxy that records what you do to it. When your function ends, Immer builds a new object by copying only the parts you touched and reusing the rest. We can build a miniature version of that mechanism (copy-on-write):

JS A miniature produce()

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Read the output carefully: the original state is untouched, the path from the root to each changed value has new objects, and todo 1 (not touched) is the same object as before. That sharing is what makes Immer efficient, and "no changes returns the same object" is why a reducer that does nothing does not trigger re-renders.

Immer in createSlice

JavaScript
// Real Redux Toolkit code (read-only)
const todosSlice = createSlice({
  name: 'todos',
  initialState: [],
  reducers: {
    todoAdded(state, action) {
      state.push({ id: action.payload.id, text: action.payload.text, done: false });
    },
    todoToggled(state, action) {
      const todo = state.find((t) => t.id === action.payload);
      if (todo) todo.done = !todo.done;
    },
    todosCleared() {
      return [];                 // or return a new value instead of mutating
    },
  },
});

Immer rules to remember:

  1. Mutate or return, never both. Either change the draft and return nothing, or return a new value and leave the draft alone. Doing both throws an error.
  2. Return undefined to keep the draft changes. An arrow function with an expression body returns its value, so (state) => state.count++ returns a number. Use braces: (state) => { state.count++; }.
  3. Drafts are proxies. Do not store them outside the reducer, and do not compare draft === originalItem. Use current(draft) (to take a snapshot for logging) or original(draft) from Redux Toolkit when you need plain values: console.log(current(state)), never console.log(state) (it prints a Proxy).
  4. Only plain objects, arrays, Map and Set are drafted (Map/Set need enableMapSet()). Class instances are not drafted unless marked [immerable] = true.
  5. Do not mutate outside reducers. Dev-mode freezing makes state.x = 1 in a component throw "Cannot assign to read only property".

Immer is also what powers updateQueryData in RTK Query and the helpers of createEntityAdapter.

Performance notes

Immer adds overhead per produce call, which is negligible for typical reducers. For very large arrays updated in tight loops (tens of thousands of items per action), batch changes in one action, or restructure to a normalized shape so each update touches one small object.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why does mutating state in a reducer usually not re-render components?

    Subscribers compare references with ===.
  2. 2. Which array method is safe to use directly on state outside Immer?

    filter returns a new array; the others mutate the original.
  3. 3. What is wrong with: todoDone: (state) => state.count++ ?

    Use braces so the function returns undefined, or return a new value without mutating.
  4. 4. What does Immer do with parts of the state you did not touch?

    Structural sharing: only the changed path is copied.

Summary

  • Mutating state hides changes from reference checks and breaks re-rendering and DevTools.
  • Immutable updates copy every level along the changed path and reuse the rest.
  • Immer drafts let createSlice reducers use mutating syntax safely.
  • Mutate or return, never both; use braces to avoid accidental returns; use current() to log.
  • Unchanged parts keep their identity (structural sharing), which keeps renders cheap.

Next: Re-renders and performance