More React answers

by Danny
Published 2 min read

Give each input a name, keep the values in one state object, and update the matching key in a single handler. Covers checkboxes, numbers, TypeScript and when to skip state entirely.

The short answer

#

Store the form in one state object, give each input a name that matches a key, and use a computed property name in a single handler to update that key. Copy the previous state rather than changing it.


_10
const [form, setForm] = useState({ name: '', email: '', role: 'dev' });
_10
_10
function handleChange(event: React.ChangeEvent<HTMLInputElement | HTMLSelectElement>) {
_10
const { name, value } = event.target;
_10
setForm((prev) => ({ ...prev, [name]: value }));
_10
}
_10
_10
<input name="name" value={form.name} onChange={handleChange} />
_10
<input name="email" value={form.email} onChange={handleChange} />

Why it happens

#

With controlled inputs, each field needs a value in state and a way to update it. Writing a separate useState and handler for every field works for two inputs, but a form with ten fields turns into a wall of almost identical code.

The change event already tells you which input changed, through event.target.name. If your state keys match the input names, one function can update any field. The square brackets in [name]: value are a JavaScript computed property name: they use the value of the variable name as the key.

You must spread the previous state because React replaces state with whatever you pass. Returning only the changed field would wipe the others.

How to fix it

#

One handler with computed keys

This is the version above, typed so TypeScript checks the keys too.


_23
type Signup = { name: string; email: string; role: string };
_23
_23
function SignupForm() {
_23
const [form, setForm] = useState<Signup>({ name: '', email: '', role: 'dev' });
_23
_23
function handleChange(
_23
event: React.ChangeEvent<HTMLInputElement | HTMLSelectElement | HTMLTextAreaElement>,
_23
) {
_23
const { name, value } = event.target;
_23
setForm((prev) => ({ ...prev, [name as keyof Signup]: value }));
_23
}
_23
_23
return (
_23
<form>
_23
<input name="name" value={form.name} onChange={handleChange} />
_23
<input name="email" type="email" value={form.email} onChange={handleChange} />
_23
<select name="role" value={form.role} onChange={handleChange}>
_23
<option value="dev">Developer</option>
_23
<option value="design">Designer</option>
_23
</select>
_23
</form>
_23
);
_23
}

Handle checkboxes and numbers

Checkboxes report their state in checked, not value, and every input's value is a string. Branch on the input type.


_11
function handleChange(event: React.ChangeEvent<HTMLInputElement>) {
_11
const { name, type, value, checked } = event.target;
_11
_11
setForm((prev) => ({
_11
...prev,
_11
[name]: type === 'checkbox' ? checked : type === 'number' ? value === '' ? '' : Number(value) : value,
_11
}));
_11
}
_11
_11
<input type="checkbox" name="newsletter" checked={form.newsletter} onChange={handleChange} />
_11
<input type="number" name="age" value={form.age} onChange={handleChange} />

Keeping an empty number field as an empty string lets the user clear it; converting straight to Number('') would turn it into 0.

Use useReducer for larger forms

When updates need validation or several fields change together, a reducer keeps that logic in one place.


_18
type Action = { type: 'field'; name: keyof Signup; value: string } | { type: 'reset' };
_18
_18
function reducer(state: Signup, action: Action): Signup {
_18
switch (action.type) {
_18
case 'field':
_18
return { ...state, [action.name]: action.value };
_18
case 'reset':
_18
return initialSignup;
_18
}
_18
}
_18
_18
const [form, dispatch] = useReducer(reducer, initialSignup);
_18
_18
<input
_18
name="email"
_18
value={form.email}
_18
onChange={(e) => dispatch({ type: 'field', name: 'email', value: e.target.value })}
_18
/>

Skip state and read FormData on submit

If you only need the values when the form is submitted, you may not need state at all. Leave the inputs uncontrolled and read them with FormData. In React 19 you can pass a function to the form's action prop and it receives the FormData directly.


_14
function SignupForm() {
_14
async function signup(formData: FormData) {
_14
const data = Object.fromEntries(formData);
_14
await saveSignup(data);
_14
}
_14
_14
return (
_14
<form action={signup}>
_14
<input name="name" defaultValue="" />
_14
<input name="email" type="email" />
_14
<button type="submit">Sign up</button>
_14
</form>
_14
);
_14
}

React resets uncontrolled fields after a successful action. Use controlled state when you need live validation, dependent fields or formatting as the user types. For large forms with complex validation, a form library such as React Hook Form saves a lot of code.

Common pitfalls

#
  • Missing or mismatched name attributes. If name does not match a state key, the handler creates a new key and the input never updates.
  • Mutating state. form[name] = value; setForm(form) changes the same object, so React may skip the update. Always create a new object.
  • Reading the event inside the updater. Destructure name and value before calling setForm, so the updater function does not depend on the event object.
  • Switching between controlled and uncontrolled. Start every field with a defined value, such as an empty string, or React warns that the input changed from uncontrolled to controlled.
  • Nested objects. Spreading only copies one level. For address.city, copy the nested object too, or flatten the form state.
#

Was this resource helpful?