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.
Immer creates a draft copy of the current state that you can safely modify.
All apparent mutations are applied to the draft, not the original state.
After the reducer runs, Immer finalizes the draft and produces a new immutable state.
This allows writing cleaner, more intuitive reducer logic without breaking Redux’s immutability rules.
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.