Course contentsShow
← React
Lesson 377 of 2,39611. useState Patterns and PitfallsFree lesson

Common Mistake: Mutating prevState

Why you must return a new reference in functional updates: mutating prevState directly breaks React's immutability contract.

Common Mistake: Mutating prevState

You'll learn why directly changing prevState in a functional update breaks React's fundamental rules and how to avoid this pitfall.

The Immutability Contract

When you use functional updates like setState(prev => ...), React gives you the current state as prev. Here's the critical rule: you must return a NEW reference, not modify the old one.

React relies on detecting changed references to know when something updated. If you mutate prevState directly and return it, you're returning the same reference—React thinks nothing changed, and your UI won't update correctly.

The Broken Pattern

// ❌ WRONG: Mutating prevState
setCart(prevCart => {
  prevCart.push(newItem); // Mutates the array!
  return prevCart; // Same reference
});

// ❌ WRONG: Mutating object properties
setUser(prevUser => {
  prevUser.name = "Alice"; // Mutates the object!
  return prevUser; // Same reference
});

Even though you're using functional updates, mutating prevState defeats the entire purpose. React may skip re-renders, and features like time-travel debugging break.

The Correct Pattern

// ✅ CORRECT: Return new array
setCart(prevCart => [...prevCart, newItem]);

// ✅ CORRECT: Return new object
setUser(prevUser => ({ ...prevUser, name: "Alice" }));

Think of prevState as a museum artifact behind glass—you can look at it, but you must create a copy to make changes.

Key Takeaway: Never mutate prevState directly in functional updates—always return a new array, object, or value to maintain React's immutability contract.