Immer Integration: Mutating Draft State
You'll learn how Redux Toolkit lets you write reducer logic that looks like mutation but remains safely immutable.
The Core Idea
Redux Toolkit includes Immer behind the scenes, which means you can write reducer code that directly modifies state — state.count++ or state.items.push(newItem) — and RTK automatically converts these "mutations" into proper immutable updates. You get the simplicity of mutable code with the safety of immutability.
How It Works
When you write reducer logic in a createSlice, RTK wraps your state in an Immer "draft." This draft is a special proxy object that tracks all your changes. When your reducer finishes, Immer creates a new immutable state object reflecting those changes — you never actually mutated the real state.
const counterSlice = createSlice({
name: 'counter',
initialState: { value: 0, history: [] },
reducers: {
increment(state) {
// Looks like mutation, but it's not!
state.value++
state.history.push(state.value)
}
}
})
Behind the scenes, Immer converts that state.value++ into something like { ...state, value: state.value + 1, history: [...state.history, state.value + 1] }.
The Mental Model Shift
Think of it like editing a Google Doc: you make changes directly to what looks like the original, but Google is actually tracking every keystroke and creating a new version. Immer does the same — it records your "edits" and produces a fresh, immutable copy.
You cannot mix patterns: either mutate the draft or return a new object, never both. Mutating the draft means no return statement needed.
Key Takeaway: Redux Toolkit's Immer integration lets you write simple, mutation-style reducer code that RTK automatically converts to immutable updates — giving you clean syntax without sacrificing Redux's core principles.