Generic onChange Handler Pattern
What you'll learn: How to write one reusable onChange handler for multiple form inputs using computed property names.
The Problem with Separate Handlers
So far, you've likely written separate onChange handlers for each input:
const [firstName, setFirstName] = useState('');
const [lastName, setLastName] = useState('');
<input value={firstName} onChange={(e) => setFirstName(e.target.value)} />
<input value={lastName} onChange={(e) => setLastName(e.target.value)} />
This works, but it's repetitive. With many inputs, you end up with lots of nearly-identical functions.
The Generic Pattern
Instead, store all form data in a single state object and use one handler for everything:
const [formData, setFormData] = useState({
firstName: '',
lastName: '',
email: ''
});
const handleChange = (e) => {
setFormData({
...formData,
[e.target.name]: e.target.value // ← Computed property name
});
};
Now all your inputs share this one handler:
<input name="firstName" value={formData.firstName} onChange={handleChange} />
<input name="lastName" value={formData.lastName} onChange={handleChange} />
<input name="email" value={formData.email} onChange={handleChange} />
How It Works
The magic is [e.target.name]: e.target.value. The brackets tell JavaScript "use the value of this expression as the property name." When the user types in the firstName input, e.target.name is "firstName", so that specific property gets updated.
Think of it like a mailroom: instead of having separate delivery people for each department, one person checks the name tag on each package and routes it accordingly.
Requirements
Each input must have a name attribute that matches a key in your state object. That's how the handler knows which property to update.
Key Takeaway: Use [e.target.name]: e.target.value with object-based state to create one reusable onChange handler for all your controlled inputs, reducing code duplication dramatically.