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

Related State That Changes Together

Recognize when grouping state into an object prevents inconsistent intermediate states.

Related State That Changes Together

You'll learn: How grouping state into an object prevents inconsistent intermediate states when multiple values must change together.

The Problem: Temporary Inconsistency

When state values always change together, storing them separately creates a dangerous gap. Imagine tracking a user's firstName and lastName with two separate useState calls. When you update both in an event handler, React batches the updates—but your logic might read state between those calls, seeing a half-updated state (old first name, new last name). This brief inconsistency can cause bugs.

// ❌ Separate state for related values
const [firstName, setFirstName] = useState('John');
const [lastName, setLastName] = useState('Doe');

function updateUser(newFirst, newLast) {
  setFirstName(newFirst);
  // Some logic here might see mismatched names!
  setLastName(newLast);
}

The Solution: Group What Changes Together

When values are conceptually tied—like coordinates (x, y), form fields, or a user's name parts—use a single object:

// ✅ Grouped state prevents inconsistency
const [user, setUser] = useState({ 
  firstName: 'John', 
  lastName: 'Doe' 
});

function updateUser(newFirst, newLast) {
  setUser({ 
    firstName: newFirst, 
    lastName: newLast 
  });
  // State is always consistent—no half-updates!
}

Now the update is atomic. React sees one state change with both values updated simultaneously.

The Mental Model

Think of a street address: street number, street name, city, and zip code. If these always change together (moving to a new address), store them as one address object. If street number might change independently (renumbering), separate state makes sense.

Key Takeaway: Group state into an object when the values always change together—this prevents intermediate inconsistent states and makes your component's logic safer.