When forms have multiple fields, managing individual useState calls becomes unwieldy. A better approach is using a single state object.
The Problem with Multiple useState
jsx// ā Gets messy with many fields const [firstName, setFirstName] = useState(''); const [lastName, setLastName] = useState(''); const [email, setEmail] = useState(''); const [phone, setPhone] = useState(''); const [address, setAddress] = useState(''); const [city, setCity] = useState(''); // ... and more
Single Object Solution
jsximport { useState } from 'react'; function RegistrationForm() { const [formData, setFormData] = useState({ firstName: '', lastName: '', email: '', phone: '', address: '', city: '' }); // Generic handler for all inputs function handleChange(e) { const { name, value, type, checked } = e.target; setFormData(prev => ({ ...prev, [name]: type === 'checkbox' ? checked : value })); } function handleSubmit(e) { e.preventDefault(); console.log(formData); } return ( <form onSubmit={handleSubmit}> <input name="firstName" value={formData.firstName} onChange={handleChange} placeholder="First Name" /> <input name="lastName" value={formData.lastName} onChange={handleChange} placeholder="Last Name" /> {/* More inputs... */} <button type="submit">Register</button> </form> ); }
Benefits
- Single handler: One
handleChangefor all inputs - Easy reset:
setFormData(initialState) - Easy submit: All data in one object
- Computed property names:
[name]: valuemaps input name to state key
Resetting the Form
jsxconst initialState = { firstName: '', lastName: '', email: '' }; function Form() { const [formData, setFormData] = useState(initialState); function handleReset() { setFormData(initialState); } // ... }
š Learn more: Choosing the State Structure