Sub topic 4
One state object for many fields
This chapter assumes you know useState, object spread syntax, destructuring, and how a single controlled input works (a value prop plus an onChange handler). If those are unfamiliar, review the previous chapter first.
The problem with one useState per field
A form with five fields would need five useState calls and five handlers. That is repetitive, and it makes the form harder to reset or submit as a unit. A better approach is to keep all values in one object and use one shared handler.
A single state object and a shared handler
import { useState } from 'react';
export default function SignupForm() {
const [form, setForm] = useState({
email: '',
plan: 'free',
subscribe: false,
});
function handleChange(e) {
const { name, type, value, checked } = e.target;
setForm((prev) => ({
...prev,
[name]: type === 'checkbox' ? checked : value,
}));
}
function handleSubmit(e) {
e.preventDefault();
console.log('Submitting', form);
}
return (
<form onSubmit={handleSubmit}>
<label>
Email
<input name="email" type="email" value={form.email} onChange={handleChange} />
</label>
<label>
Plan
<select name="plan" value={form.plan} onChange={handleChange}>
<option value="free">Free</option>
<option value="pro">Pro</option>
</select>
</label>
<label>
<input
name="subscribe"
type="checkbox"
checked={form.subscribe}
onChange={handleChange}
/>
Send me updates
</label>
<button type="submit">Sign up</button>
</form>
);
}How the handler works
Three pieces make the shared handler work.
- The
nameattribute is the state key. Each input'snamematches a key in the state object. The handler readse.target.nameto know which field changed. - Computed property names. The expression
[name]: ...uses the variable's value as the key. Ifnameis"email", it setsemail. - Spread copies the rest.
...prevcopies every existing field, and the new key overwrites only the one that changed. React state must be replaced, not mutated, so you always return a new object.
The checkbox is the exception. Its text is not in value. Its state is in checked, so the handler picks checked when type === 'checkbox'.
Why the functional update
The handler calls setForm((prev) => ...) instead of setForm({ ...form, ... }). The function form receives the latest state, so it stays correct when several updates are queued in the same event. It also avoids reading a stale form from the render that created the handler.
Common errors
- Missing or mismatched
name. If an input has noname, the handler writes to the key"". If the name has a typo, you add a new key and the intended field never changes. - Reading
e.targetinside the updater. In older React versions, events were pooled ande.targetcould be cleared before the updater ran. Destructure first, as shown, so the code is safe in every version. - Mutating state. Writing
form[name] = valueand callingsetForm(form)passes the same object. React sees no change and may skip the re-render. - Uninitialized keys. If
emailis missing from the initial object, the input starts withvalue={undefined}. React then treats it as uncontrolled and warns when it later becomes controlled. Give every field an initial value. - Nested objects. Spread is shallow. For
form.address.city, you must also copyaddress. Flat state avoids this.
Exercise
A text input has name="username" but the state object only has the keys email and password. The shared handler is the one shown above. What happens when the user types, and how do you fix it?
Show answer
The handler adds a new username key to the state, because [name] creates any key it is given. The inputs bound to email and password are unaffected. The username input has no matching initial key, so its value is undefined at first and React warns about switching from uncontrolled to controlled. Fix it by adding username: '' to the initial state.