Form State: When Objects Win
What you'll learn: Why storing all form fields in a single state object (instead of separate useState calls) often makes forms cleaner and easier to maintain.
The Problem with Multiple useState Calls
Imagine a registration form with name, email, password, and confirmPassword fields. You could create four separate useState calls:
const [name, setName] = useState('');
const [email, setEmail] = useState('');
const [password, setPassword] = useState('');
const [confirmPassword, setConfirmPassword] = useState('');
But now you need four separate handler functions, and your component gets cluttered fast.
The Object Approach Shines
When you have related state that changes together (like form fields that all submit as one unit), a single state object wins:
const [formData, setFormData] = useState({
name: '',
email: '',
password: '',
confirmPassword: ''
});
Dynamic Key Updates: The Secret Sauce
The magic happens with a single reusable handler using bracket notation to dynamically update any field:
const handleChange = (e) => {
const { name, value } = e.target;
setFormData(prev => ({
...prev,
[name]: value // Dynamic key update!
}));
};
Now every input can use the same handler:
<input name="email" value={formData.email} onChange={handleChange} />
<input name="password" value={formData.password} onChange={handleChange} />
The name attribute on each input tells the handler which field to update in the state object.
Why This Wins
- One handler instead of four (or ten!)
- Easy to submit:
formDatais already an object ready to send - Clear organization: all form state lives together
- Scales beautifully as you add more fields
Key Takeaway: For forms with multiple related fields, storing state as a single object with dynamic key updates ([name]: value) keeps your code DRY and maintainable.