Part 03 / Topic 4 of 7
Mutating state directly: a real bug, not a theoretical rule
Section 1's ClickCounter only ever gives React a new value through setCount. examples/03_mutating_state_directly.jsx shows what happens when a component skips the setter and changes the state value's contents directly instead:
// examples/03_mutating_state_directly.jsx
export function CartBroken() {
const [items, setItems] = useState([]);
function addItemBroken(name) {
items.push(name);
}
return (
<div>
<p>Items in cart: {items.length}</p>
<button onClick={() => addItemBroken("Toor Dal 1kg")}>Add Toor Dal</button>
</div>
);
}
.push() really does add the item to the same array useState is holding onto - this is not a silent no-op on the data. But setItems is never called, so React has no idea anything changed, and never re-renders. Clicking "Add Toor Dal" twice really leaves the screen stuck at "Items in cart: 0" (examples/03_mutating_state_directly.test.jsx) - no error, no warning, just a wrong-looking screen, exactly the same silent-failure shape as Part 2's props-mutation bug. CartFixed, in the same file, fixes it with the one change that matters - build a brand-new array first, then hand that new array to the setter:
// examples/03_mutating_state_directly.jsx
export function CartFixed() {
const [items, setItems] = useState([]);
function addItemFixed(name) {
setItems([...items, name]);
}
// ...
}
A new array reference is exactly the signal React needs; clicking "Add Toor Dal" twice on CartFixed really moves the count from 0 to 1 to 2 (examples/03_mutating_state_directly.test.jsx). The rule generalizes past arrays: never call .push(), .splice(), .sort(), or assign into an object's property directly on a piece of state - build a new array or object (spread, .map(), .filter()) and pass that to the setter.
Done here? The practice set for Part 3 — including the solutions — is on the part page.