03 / 13

Why can we 'mutate' state directly in Redux Toolkit reducers?

Understanding State Mutation with Immer in Redux Toolkit

In Redux Toolkit, you can appear to 'mutate' the state directly inside reducers because it uses the Immer library under the hood. Immer wraps your reducer logic and tracks all state changes, then produces a new, immutable state based on those changes.

Why Mutation Appears to Work
  1. 1

    Immer creates a draft copy of the current state that you can safely modify.

  2. 2

    All apparent mutations are applied to the draft, not the original state.

  3. 3

    After the reducer runs, Immer finalizes the draft and produces a new immutable state.

  4. 4

    This allows writing cleaner, more intuitive reducer logic without breaking Redux’s immutability rules.

Example: Mutating State Safely with Immer

So, while reducers in Redux Toolkit look like they mutate state, Immer ensures they remain pure functions by automatically generating the next immutable state from the modifications.