The Single Object Approach: Pros and Cons
You'll learn when grouping related state into a single object improves organization—and when it makes updates unnecessarily complex.
The Choice: Multiple useState vs. One Object
You've seen multiple useState calls work well, but what if your state feels like it belongs together? Instead of:
const [firstName, setFirstName] = useState('');
const [lastName, setLastName] = useState('');
const [email, setEmail] = useState('');
You could group them:
const [user, setUser] = useState({
firstName: '',
lastName: '',
email: ''
});
The Pros: Organization and Clarity
Related data stays together. If these values always represent one logical entity (like a user form), a single object makes that relationship explicit. You're documenting through structure that these pieces belong together.
Fewer state variables to manage. Your component has one state declaration instead of three, reducing visual clutter.
The Cons: Update Complexity
Here's the catch: state updates don't merge (remember lesson 349?). You must manually spread the old state:
// Wrong - loses other properties!
setUser({ firstName: 'Jane' });
// Right - preserves other properties
setUser(prev => ({ ...prev, firstName: 'Jane' }));
Every update requires spreading, even for one property. With separate useState calls, setFirstName('Jane') is simpler.
The Analogy
Think of a filing cabinet. One drawer labeled "User Info" (single object) vs. three drawers labeled "First Name," "Last Name," "Email" (separate states). The single drawer is neater if you always access these together, but updating one file means pulling out the entire drawer and reorganizing it.
Key Takeaway: Use a single state object when values are tightly related and often updated together; prefer multiple useState calls when values change independently—it avoids manual spreading.