Immutable Updates: Creating New Objects
What you'll learn: Why your reducer must always return brand-new objects instead of modifying the existing state directly.
The Golden Rule of Reducers
Remember that your reducer is a pure function. One critical requirement of purity is never mutating the input parameters. When React calls your reducer with the current state, that object is read-only. You must return a new object to represent the next state.
Why Immutability Matters
Think of state like a historical photograph. You don't draw on the original photo to show changes—you take a new picture. React compares the old state object to the new one by reference. If you mutate the existing object and return it, React sees the same reference and thinks nothing changed, so it won't re-render.
The Wrong Way
function cartReducer(state, action) {
if (action.type === 'ADD_ITEM') {
state.items.push(action.item); // ❌ WRONG: mutating state
return state; // Same object reference
}
}
The Right Way
function cartReducer(state, action) {
if (action.type === 'ADD_ITEM') {
return {
...state, // Spread existing properties
items: [...state.items, action.item] // New array with new item
};
}
}
You're creating a new object with the spread operator (...state), and a new array with the spread operator plus the new item. The original state parameter remains untouched.
Key Takeaway: Always return fresh objects and arrays from your reducer—never modify the state parameter directly. This ensures React detects changes and updates your UI correctly.