Skip to content
Tutorials Center
My learning

Topics

Lesson 14 of 41 ยท Redux Toolkit

Immer in Redux Toolkit Reducers

Understand how Immer lets Redux Toolkit reducers look like mutation yet stay immutable. Learn the mutate-or-return rule, current and original, auto-freezing and the common Immer pitfalls.

Writing immutable updates by hand is tedious and error-prone, as you saw with nested spreads. Redux Toolkit solves this with Immer. Inside a createSlice reducer you receive a draft of the state, and you may change it with ordinary assignments, push, delete and so on. Immer records your changes and produces a brand-new immutable state, while the original stays untouched.

This is the single most surprising thing about Redux Toolkit for newcomers, because "never mutate state" was the first rule you learned. The rule has not changed: you never mutate the real state; you mutate a temporary draft, and Immer does the safe copying.

Immer is part of @reduxjs/toolkit, which cannot be loaded in our editor. The runnable examples use a stand-in produce that copies the state, runs your code on the copy and reuses unchanged parts (structural sharing). Real Immer uses Proxies instead of copying everything up front, so it is faster, but the rules and results you see here match it.

How it works

flowchart LR
    S["Current state (frozen)"] -->|"produce"| D["Draft (a proxy)"]
    D -->|"your code mutates the draft"| M["Recorded changes"]
    M -->|"finish"| N["New immutable state"]
    S -.->|"unchanged parts are reused"| N

Immer wraps the state in a draft, tracks writes, then builds the next state by copying only what changed.

Compare the same reducer both ways:

JavaScript
// hand-written immutable update
case 'todos/toggled':
  return {
    ...state,
    items: state.items.map((t) => (t.id === action.payload ? { ...t, done: !t.done } : t)),
  };

// createSlice with Immer
toggled(state, action) {
  const todo = state.items.find((t) => t.id === action.payload);
  if (todo) todo.done = !todo.done;
},

The rule: mutate OR return, never both

A case reducer may do exactly one of these:

  1. Mutate the draft and return nothing (undefined).
  2. Return a new value and leave the draft alone.

Doing both throws an error. Mutating and returning is ambiguous: which version wins?

JS Mutate, return, or both?

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

No output.

Case 4 is the classic trap. A reducer written as an arrow function with an expression body, (state) => state.count += 1, returns the new number and changed the draft, so Immer reports the same error as case 5. (If it returned a value without changing anything, that value would silently replace your state.) Use a block body with braces: (state) => { state.count += 1; }. In a createSlice the shorthand method syntax (incremented(state) { ... }) avoids the problem.

To replace the whole state, return the new value (case 2). To reset to the starting state, return initialState (or slice.getInitialState()).

Drafts are not the real objects

Inside a case reducer, state is a proxy. Two consequences:

  • console.log(state) prints a confusing Proxy object. Use current(state) from Toolkit to get a plain snapshot of the draft's present value. original(state) gives the state as it was before your changes.
  • Do not store a draft somewhere that lives past the reducer (in a global or a closure). It becomes invalid once the reducer finishes.
JavaScript
import { createSlice, current, original } from '@reduxjs/toolkit';

const slice = createSlice({
  name: 'debug',
  initialState: { n: 0 },
  reducers: {
    bumped(state) {
      state.n += 1;
      console.log(current(state));  // { n: 1 }  plain object, not a Proxy
      console.log(original(state)); // { n: 0 }
    },
  },
});

What you can and cannot do with a draft

You may Notes
Assign to properties and indexes state.user.name = 'Ada', state.items[2] = x
Use mutating array methods push, pop, splice, sort, reverse all work on draft arrays
delete properties delete state.byId[id]
Put new plain objects into the draft They become part of the state
Read freely find, filter, map, comparisons
Watch out for Why
Asynchronous code in a reducer The draft is only valid while the reducer runs (and reducers must be sync anyway)
Class instances, Map, Set Not drafted by default; keep state as plain objects/arrays (or enable Immer's plugins deliberately)
Comparing a draft object with an outside object by === A draft child is a proxy, so it never equals the original object
Mixing drafts into outside data Do not push draft objects into non-state structures

Auto-freezing and no-op updates

Immer freezes the state it produces (Object.freeze, deep), so an accidental mutation outside a reducer throws a TypeError in strict mode instead of silently corrupting the store. Another gift: if your reducer changes nothing, Immer returns the same reference, so no subscriber sees a change.

JS Frozen results and no-op updates

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

No output.

Writing good case reducers with Immer

  • Prefer the simplest code that reads clearly. state.items.push(item) is better than a spread.
  • Look things up, then change them. const todo = state.byId[id]; if (todo) todo.done = true; โ€” always guard against a missing record.
  • Return for replacements: return initialState or return action.payload to replace the entire state.
  • Avoid heavy work in the reducer. Immer's proxy has overhead; sorting or filtering thousands of items in every action is slow. Normalise data and derive lists in selectors.
  • Mutate in one place. Hiding mutations in helper functions that receive the draft works, but name them clearly (applyDiscount(draft, ...)).

Immer outside createSlice

createSlice and createReducer use Immer for you. You can also call produce yourself (from immer, or re-exported as createNextState in Toolkit) in any code that needs safe updates, including plain useReducer reducers.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Is it a violation of Redux rules to write state.count += 1 inside a createSlice reducer?

    Immer gives the reducer a draft, records changes and produces a new immutable state. The original state is untouched.
  2. 2. What happens if a case reducer both modifies the draft and returns a new object?

    Mutate OR return. Doing both is ambiguous and Immer reports an error.
  3. 3. Why is (state) => state.count += 1 a bad reducer in a createSlice?

    An expression body returns its value. Use a block body or the method shorthand so the reducer returns undefined.
  4. 4. How do you log the current value of a draft?

    current(draft) returns a plain snapshot; logging the draft directly prints a Proxy.

Summary

  • Toolkit reducers receive an Immer draft; mutating it is safe and produces a new immutable state.
  • Either mutate the draft or return a new value, never both; beware arrow functions with expression bodies, which return a value.
  • Return a value to replace the whole state; assigning to the state parameter does nothing.
  • Use current(state) and original(state) to inspect drafts; do not keep drafts around.
  • Immer freezes results and returns the same reference when nothing changed.

Next: createAction and createReducer