React / 67
Immer: writing reducers that look like mutation
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 changed2 · your reducer
Edits the draft
state.items.push(burger)looks like mutation, is only recorded3 · 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-isRedux 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 item | state.items.push(item) |
| Remove an item | state.items = state.items.filter((i) => i.id !== id) |
| Update one field | const item = state.items.find((i) => i.id === id); if (item) item.qty += 1 |
| Reset the slice | return initialState |
| Replace a whole value | return action.payload |
| Change a number or string slice | return 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:
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.
