The Single State Object Pattern
What you'll learn: How to decide between grouping all form fields into one useState object versus managing each field with its own separate state variable.
The Two Approaches
When building forms in React, you face a fundamental choice:
// Approach 1: Single state object
const [formData, setFormData] = useState({
email: '',
username: '',
password: ''
});
// Approach 2: Multiple state variables
const [email, setEmail] = useState('');
const [username, setUsername] = useState('');
const [password, setPassword] = useState('');
Both work, but they have different tradeoffs.
Single Object: The Tradeoffs
Pros:
- Easier to pass around (one variable instead of many)
- Simpler to reset the entire form:
setFormData(initialState) - Natural fit when form state has nested structure
- Less boilerplate for many fields
Cons:
- Must spread previous state when updating:
setFormData(prev => ({ ...prev, email: value })) - Forgetting the spread operator wipes out other fields (common gotcha!)
- Every field update causes the whole object to be "new," though React handles this efficiently
Think of it like: A single notebook with sections versus separate notebooks for each subject. The single notebook keeps everything together but requires flipping pages carefully.
Multiple Variables: The Tradeoffs
Pros:
- Simpler updates:
setEmail(value)— no spreading needed - Harder to accidentally lose data
- More granular control per field
Cons:
- More lines of code for large forms
- Passing all values to child components gets verbose
- Resetting means calling multiple setters
The Gotcha You Must Remember
With a single object, this destroys your data:
setFormData({ email: value }); // ❌ Loses username and password!
Always spread: setFormData(prev => ({ ...prev, email: value })) ✅
Key Takeaway: Use a single state object when you have many related fields or nested structure; use multiple variables for small, simple forms where each field updates independently.