Sub topic 4
One state object for many fields
This chapter assumes you know how a controlled input works (value plus onChange), how useState returns a value and a setter, and how object spread and computed property names work in JavaScript. If any of these are unfamiliar, review them first.
The problem with one useState per field
The previous chapter built a controlled input with one state variable. That approach scales badly. A form with eight fields needs eight useState calls and eight handlers, and resetting the form means calling eight setters.
An alternative is to keep all field values in one object. The object is the single source of truth for the whole form, and one change handler updates whichever key changed.
| Approach | Strengths | Weaknesses |
|---|---|---|
| One `useState` per field | Simple, and each setter is trivial | Many handlers, and reset and submit need every variable |
| One state object | One handler, one reset, one value to submit | You must copy the object correctly on every update |
Neither approach is wrong. For two or three unrelated fields, separate state variables are fine. For a form that you submit as a unit, an object is usually easier to manage.
The shared change handler
The pattern relies on two features. Each input has a name attribute that matches a key in the state object. The handler uses a computed property name ([name]) to update that key.
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>
);
}Each onChange call follows the same path, shown below.
How the update works
The setter call has three parts.
setForm((prev) => ...)passes a function, called an updater. React calls it with the latest state, so you never work from a stale copy....prevcopies every existing key into a new object. Without it, the new state would contain only the changed field, and the other fields would becomeundefined.[name]: ...goes after the spread, so it overwrites the old value for that one key.
The order matters. If you write { [name]: value, ...prev }, the old value from prev overwrites your change, and the input appears to ignore typing.
Why read from e.target before the updater
The updater runs later, during React's processing of the update. The handler destructures e.target first, outside the updater, so the updater only uses plain local values. Reading e.target.value inside the updater is a common source of bugs. Older React versions reused event objects, and even in current versions it ties the updater to a mutable DOM node.
Choosing the checked or value property
Text inputs, selects and textareas report their content in e.target.value. A checkbox reports its state in e.target.checked, and its value is a fixed string ("on" by default). The shared handler therefore needs the branch on type.
Two consequences follow.
- A checkbox must be wired with
checked={form.subscribe}, notvalue. - The initial state for a checkbox must be a boolean. If it were
'', the box would show as unchecked but the first click would storetruewhile the starting value had a different type.
Radios and textareas are covered in the next chapter. Radios share one name and use checked={form.plan === 'pro'}, so the same handler works with them.
Common errors
Mutating state directly
This code looks reasonable and does not work:
function handleChange(e) {
form[e.target.name] = e.target.value; // mutates the existing object
setForm(form); // same reference
}React compares the new state to the old state by reference. Because form is the same object, React sees no change and skips the re-render. The input then appears frozen. Always build a new object.
The name does not match the key
If the input says name="e-mail" but the state key is email, the handler creates a new e-mail key. The email input stays at its old value and does not update as you type. No error is shown. When one field misbehaves, compare its name to the state key first.
Missing initial keys
If the state starts as {} and an input reads value={form.email}, the value is undefined at first. React treats that input as uncontrolled. When the value later becomes a string, React logs a warning about switching from uncontrolled to controlled. Give every field an initial value, even an empty string.
Numbers arrive as strings
Even with type="number", e.target.value is a string. Convert when you submit or validate:
const payload = { ...form, quantity: Number(form.quantity) };Do not convert inside the handler with Number(value) unless you have thought through the empty input case. Number('') is 0, so a user who clears the field would see a 0 appear.
Nested objects
Real forms sometimes group values, such as an address with street and city. Spread copies only one level, so a nested update must copy each level it changes.
import { useState } from 'react';
export default function ShippingForm() {
const [form, setForm] = useState({
name: '',
address: { street: '', city: '' },
});
function handleChange(e) {
const { name, value } = e.target;
setForm((prev) => ({ ...prev, [name]: value }));
}
function handleAddressChange(e) {
const { name, value } = e.target;
setForm((prev) => ({
...prev,
address: { ...prev.address, [name]: value },
}));
}
return (
<form>
<input name="name" value={form.name} onChange={handleChange} />
<input name="street" value={form.address.street} onChange={handleAddressChange} />
<input name="city" value={form.address.city} onChange={handleAddressChange} />
</form>
);
}If address is replaced by { [name]: value } without the inner spread, the other address field is lost. Two handlers, one for each level, keep each function simple. If you find yourself nesting three levels deep, flatten the state (addressStreet) or reconsider the data shape.
Tips for keeping the pattern tidy
Trade-offs to know about
A single object means every keystroke creates a new object and re-renders the whole form component. For a form with a dozen fields this cost is negligible. It matters only for very large forms or expensive child components, and a later chapter covers that case.
The shared handler also hides field-specific logic. If one field needs formatting (a phone number mask) or a side effect, give it its own handler and leave the generic one for the rest. Mixing both in one form is normal.
Summary of the pattern
- Store all values in one object with an initial value for every key.
- Give each input a
nameequal to its state key. - Use
valuefor text-like inputs andcheckedfor checkboxes. - Update with
setForm((prev) => ({ ...prev, [name]: nextValue })). - Never mutate
form. Copy each level you change.
Exercise
A teammate's form uses const [form, setForm] = useState({ title: '', done: false }). Typing in the title input does nothing, and the code is function handleChange(e) { setForm({ [e.target.name]: e.target.value, ...form }); }. The input has name="title". What is wrong, and how do you fix it?
Show answer
The spread comes after the computed key, so the old form.title overwrites the new value on every change. Put the spread first and use an updater: setForm((prev) => ({ ...prev, [name]: value })), with name and value read from e.target before the call. Also, this handler writes e.target.value for the done checkbox, so it needs the type === 'checkbox' ? checked : value branch.
Exercise
You add <input name="age" type="number" value={form.age} onChange={handleChange} /> with age: 0 in the initial state. A user clears the field, and the input shows an empty box, then you submit and the server receives the string "". How would you handle this?
Show answer
Keep age as a string in state while the user edits, since e.target.value is always a string. Convert at submit time, for example const age = form.age === '' ? null : Number(form.age), so an empty field is distinguishable from the number 0. Initialize age to '' instead of 0 so the first render matches what the user sees.