Functional Updates with Objects
What you'll learn: How to safely update object state in React by spreading the previous state inside a functional update.
Why This Matters
You've already learned functional updates with primitive values like numbers. But when your state is an object, you face a new challenge: if you only update one field, you might accidentally lose the other fields.
const [user, setUser] = useState({ name: 'Alice', age: 30 });
// ❌ This REPLACES the entire object — age is gone!
setUser({ name: 'Bob' });
The Pattern: Spread Previous State
The solution is to use the functional update pattern with the spread operator to preserve existing fields:
setUser(prev => ({ ...prev, name: 'Bob' }));
Here's what happens:
- React gives you the previous state (
prev) - You spread it (
...prev) to copy all existing fields - You override just the field(s) you want to change
Think of it like editing a form: you don't throw away the entire form just to change one field — you keep everything else and update that one value.
Complete Example
const [user, setUser] = useState({ name: 'Alice', age: 30, city: 'NYC' });
// ✅ Update name, keep age and city
setUser(prev => ({ ...prev, name: 'Bob' }));
// ✅ Update age, keep name and city
setUser(prev => ({ ...prev, age: prev.age + 1 }));
After both updates, your state still has all three fields: name, age, and city.
Key Takeaway: Always use setState(prev => ({ ...prev, field: newValue })) when updating object state to avoid accidentally deleting other properties — the spread operator copies the old fields before you override specific ones.