Nested State Structures for Forms
What you'll learn: How to organize form data using nested objects that mirror your API's expected format and logically group related fields.
The Flat State Problem
When forms grow complex—think user profiles with addresses, payment info, and preferences—storing everything in flat state becomes messy:
const [firstName, setFirstName] = useState('');
const [lastName, setLastName] = useState('');
const [street, setStreet] = useState('');
const [city, setCity] = useState('');
const [zipCode, setZipCode] = useState('');
// ...20 more fields
This creates dozens of individual state variables and makes submitting to an API painful—you have to manually reconstruct the nested structure your backend expects.
The Nested Solution
Instead, structure your state to match your API's shape from the start:
const [formData, setFormData] = useState({
personalInfo: {
firstName: '',
lastName: ''
},
address: {
street: '',
city: '',
zipCode: ''
}
});
Why this wins: Related fields stay grouped, your component has one state variable instead of twenty, and submission becomes fetch('/api/user', { body: JSON.stringify(formData) }) with zero transformation.
Updating Nested State
Use the spread operator to update deeply:
const handleStreetChange = (e) => {
setFormData(prev => ({
...prev,
address: {
...prev.address,
street: e.target.value
}
}));
};
Yes, the syntax is more verbose per field, but the organizational clarity pays off immediately in larger forms.
Key Takeaway: Structure form state as nested objects that mirror your API's expected payload—it reduces state variables, groups related data logically, and eliminates the need for transformation before submission.