Updating Object State: The Spread Trap
What You'll Learn
You'll discover why setState({ ...state, field: value }) can accidentally lose data if you're not spreading carefully enough.
The Hidden Danger of Shallow Spreading
When you store an object in state and want to update just one field, you might write:
const [user, setUser] = useState({ name: 'Alice', age: 30 });
// Later...
setUser({ ...user, age: 31 });
This works perfectly—you've spread all existing properties and overridden age. But what if your state object is nested?
const [user, setUser] = useState({
name: 'Alice',
address: { city: 'NYC', zip: '10001' }
});
// TRAP: This loses the zip code!
setUser({ ...user, address: { city: 'Boston' } });
The spread operator (...) only copies one level deep. When you write address: { city: 'Boston' }, you're completely replacing the address object, not merging into it. The zip field vanishes.
The Safe Pattern
To update nested objects, you must spread at every level:
setUser({
...user,
address: { ...user.address, city: 'Boston' }
});
Now zip survives because you spread the old address object first, then override just city.
Think of It Like Photocopying
The spread operator is like making a photocopy—it only copies what's visible on the surface. If the original document references another folder (a nested object), the copy just references the same folder. You need to manually copy each nested folder too.
Key Takeaway: The spread operator (...) only copies one level deep. Always spread nested objects explicitly, or you'll lose their inner fields when updating state.