🚨 React Re-render Methods: Reference Matters!
Source: Dev.to
Mutating Methods (Do NOT change reference)
These methods modify the same array/object in memory, so using them directly on React state may not trigger a re‑render:
pushpopshiftunshiftsortreversesplicefillcopyWithin
// ❌ Wrong: mutating the existing state
setItems(prev => {
prev.push(1); // mutates `prev`
return prev; // same reference → no re‑render
});
Safe Methods (Create a new reference)
These methods return a new array, allowing React to detect the change:
mapfilterconcatsliceflatflatMaptoSortedtoReversedtoSpliced
// ✅ Correct: returns a new array
setItems(prev => [...prev, 1]); // spreads into a new array
Key Rule to Remember
React compares references, not the values inside them. Updating state with a new reference ensures a re‑render.
One‑line Takeaway
“Mutating methods keep the same reference, so React won’t re‑render. Always return a new reference when updating state.”