Skip to content
ClapelloNotes by Barath
ReactCh 12 · 4/6
Core4 min readUpdated

React / 67

Immer: writing reducers that look like mutation

TL;DR

Inside createSlice you can write state.items.push(x). Immer records the change on a draft and builds a new, immutable state for you.

How Immer works

1 · current state

Frozen

{ items: [dosa], user: {…} }never changed
Immer makes a draft

2 · your reducer

Edits the draft

state.items.push(burger)looks like mutation, is only recorded
Immer finishes

3 · next state

Brand new object

{ items: [dosa, burger], user: {…} }

what changed, by reference

next === prev // false: new objectnext.items === prev.items // false: you changed itnext.user === prev.user // true: reused as-is
Immer hands your reducer a draft. You change the draft; Immer builds a new state and reuses every part you didn't touch.

Redux Toolkit runs every reducer in createSlice through Immer. Your reducer gets a draft: a stand-in object (a JavaScript Proxy) that records every change you make. When your reducer finishes, Immer builds the next state from those records. The old state is never touched, and every part you didn't change is reused as-is, so unchanged components can skip re-rendering.

Same reducer, two ways

Bumping one dish's quantity:

incrementQty(state, action) {
  return {
    ...state,
    items: state.items.map((item) =>
      item.id === action.payload ? { ...item, qty: item.qty + 1 } : item
    ),
  };
}
incrementQty(state, action) {
  const item = state.items.find((i) => i.id === action.payload);
  if (item) item.qty += 1;
}

Both are correct inside createSlice. The Immer version says what you mean.

The one rule: change the draft OR return a new value

You want to…Write
Add an itemstate.items.push(item)
Remove an itemstate.items = state.items.filter((i) => i.id !== id)
Update one fieldconst item = state.items.find((i) => i.id === id); if (item) item.qty += 1
Reset the slicereturn initialState
Replace a whole valuereturn action.payload
Change a number or string slicereturn state + 1 (you can't "mutate" a primitive)

Changing the draft and returning nothing: fine. Returning a new value and not touching the draft: fine. Doing both in one reducer: Immer throws an error.

A full cart slice using both styles:

src/store/cartSlice.js
import { createSlice } from "@reduxjs/toolkit";
 
const initialState = { items: [] };
 
const cartSlice = createSlice({
  name: "cart",
  initialState,
  reducers: {
    removeItem: (state, action) => {
      const index = state.items.findIndex((i) => i.id === action.payload);
      if (index !== -1) state.items.splice(index, 1); // change the draft
    },
    clearCart: () => initialState, // return a new value
  },
});

Don't

Reassigning state

clearCart: (state) => {
  state = initialState; // only changes a local variable
},

Do

Return the new value

clearCart: () => initialState,

Gotchas

Recall

Can you answer these?

0/4

Answer out loud (or in your head) before you tap. That's what makes it stick.

Saved on this device only. No login.