Sub topic 7
Controlled Inputs with onChange
This chapter assumes you know JavaScript arrow functions, basic JSX, components and props, and the useState hook. You should also have seen how to attach a handler such as onClick and how to read event.target. Here you will learn how React makes state the single source of truth for a form field, and where that pattern commonly goes wrong.
What "controlled" means
A form field such as <input> keeps its own value in the browser's DOM (Document Object Model, the browser's live tree of page elements). When you type, the DOM updates that value without asking React.
A controlled input hands that job to React. You store the value in state and pass it to the element through the value prop. Every change goes through a handler that updates the state. The element never shows anything that React did not give it.
The pattern has two parts:
value={state}tells the input what to display.onChange={handler}tells React what to do when the user edits it.
import { useState } from 'react';
function NameField() {
const [name, setName] = useState('');
return (
<label>
Name
<input value={name} onChange={e => setName(e.target.value)} />
</label>
);
}The render and event cycle
When the user presses a key, the browser fires an input event. React calls your onChange handler with an event object. The handler reads e.target.value, which is the text the field would contain after the keystroke. It then calls the state setter. React re-renders the component, and the input receives the new value.
This happens on every keystroke, so a controlled input re-renders its component each time. For small forms this cost is negligible.
onChange in React differs from the DOM change event
In plain HTML, the change event on a text input fires only when the field loses focus after being edited. React's onChange behaves like the DOM input event instead. It fires on every edit, including typing, pasting, cutting, and drag-and-drop of text.
This is deliberate. A controlled input has to learn about each edit immediately, because it must re-render with the new value before the user types the next character.
Value must never be undefined or null
An input is controlled when its value prop is not undefined. If you start with undefined and later pass a string, React warns that the input switched from uncontrolled to controlled. A null value triggers a similar warning.
This often happens when state comes from a server response that has not loaded yet:
import { useState } from 'react';
function ProfileForm({ initialName }) {
// initialName may be undefined on the first render
const [name, setName] = useState(initialName ?? '');
return <input value={name} onChange={e => setName(e.target.value)} />;
}Use ?? '' (or a default value) so the input always receives a string.
A value without onChange is read-only
If you pass value and omit onChange, React renders the field as read-only and logs a warning. Typing does nothing, because React keeps putting the old value back.
The following field cannot be edited:
function Stuck() {
return <input value="fixed" />;
}There are three valid fixes:
- Add an
onChangethat updates state, as shown above. - Add the
readOnlyattribute if you really want a fixed value. - Use
defaultValueinstead ofvalueto make an uncontrolled input that only sets the starting text.
Other input types use different props
Not every field uses value and e.target.value. The table lists the common cases.
| Element | Prop that holds state | Read from the event |
|---|---|---|
| `<input type="text">` | `value` | `e.target.value` |
| `<textarea>` | `value` | `e.target.value` |
| `<select>` | `value` on the `<select>` | `e.target.value` |
| `<input type="checkbox">` | `checked` | `e.target.checked` |
| `<input type="radio">` | `checked` on each radio | `e.target.value` |
| `<input type="number">` | `value` | `e.target.value` (still a string) |
Two details matter here. In React, <textarea> takes its text from value, not from child text as in HTML. And <select> takes its selected option from value on the <select> element, not a selected attribute on an <option>.
import { useState } from 'react';
function Preferences() {
const [plan, setPlan] = useState('free');
const [subscribed, setSubscribed] = useState(false);
const [notes, setNotes] = useState('');
return (
<form>
<select value={plan} onChange={e => setPlan(e.target.value)}>
<option value="free">Free</option>
<option value="pro">Pro</option>
</select>
<label>
<input
type="checkbox"
checked={subscribed}
onChange={e => setSubscribed(e.target.checked)}
/>
Subscribe to updates
</label>
<textarea value={notes} onChange={e => setNotes(e.target.value)} />
</form>
);
}Number inputs return strings
e.target.value is always a string, even for type="number". If you store it and later do arithmetic, '2' + '3' gives '23'. Convert deliberately:
import { useState } from 'react';
function Quantity() {
const [qty, setQty] = useState(1);
function handleChange(e) {
const next = e.target.valueAsNumber;
setQty(Number.isNaN(next) ? 0 : next);
}
return <input type="number" value={qty} onChange={handleChange} />;
}valueAsNumber returns NaN when the field is empty, so the handler checks for it. Storing the raw string in state and converting on submit is often simpler, because it lets the user clear the field while typing.
Managing several fields with one handler
A form with many fields does not need one state variable and one handler per field. Give each input a name attribute and store the values in one object. The handler uses the name to decide which key to update.
import { useState } from 'react';
function ContactForm() {
const [form, setForm] = useState({ name: '', email: '', message: '' });
function handleChange(e) {
const { name, value } = e.target;
setForm(prev => ({ ...prev, [name]: value }));
}
return (
<form>
<input name="name" value={form.name} onChange={handleChange} />
<input name="email" value={form.email} onChange={handleChange} />
<textarea name="message" value={form.message} onChange={handleChange} />
</form>
);
}Two points are worth noting. The square brackets in [name] are a computed property key, so the key comes from the variable. And the updater copies the previous object with ...prev because React state must be replaced, not mutated. Setting form.name = value directly would not trigger a re-render.
Destructure name and value from e.target before calling the setter. The updater function runs later, and reading e.target inside it is fragile if you ever move code around. Reading the values first avoids that.
Transforming input as the user types
Because every change passes through your code, you can reject or reshape the value before it reaches state.
import { useState } from 'react';
function PostalCode() {
const [code, setCode] = useState('');
function handleChange(e) {
const digits = e.target.value.replace(/\D/g, '').slice(0, 5);
setCode(digits);
}
return <input value={code} onChange={handleChange} inputMode="numeric" />;
}If the user types a letter, the handler strips it and sets the same state as before. React sees no change in state and the input keeps its old text. The keystroke appears to be ignored.
Derived values should not be state
If a value can be computed from other state, compute it during render. Do not store it and sync it in the handler.
import { useState } from 'react';
function Search({ items }) {
const [query, setQuery] = useState('');
const visible = items.filter(item =>
item.toLowerCase().includes(query.toLowerCase())
);
return (
<div>
<input value={query} onChange={e => setQuery(e.target.value)} />
<ul>
{visible.map(item => (
<li key={item}>{item}</li>
))}
</ul>
</div>
);
}Here query is the only state. The filtered list is recalculated on each render, so the two can never disagree.
Common errors
- Calling the handler during render.
onChange={setName(e.target.value)}runs immediately andeis undefined. Pass a function:onChange={e => setName(e.target.value)}. - Forgetting the
checkedprop for checkboxes. Usingvalueon a checkbox does not control whether it is ticked. - Mutating an object in state. Always create a new object or array with a spread.
- Defining the component inside another component. React sees a new component type on every render, so the input is recreated and loses focus after each keystroke.
- Using an unstable
keyon an input. Changing thekeyremounts the field and resets focus and content.
When to choose uncontrolled inputs
Controlled inputs are the default because they make validation, formatting, and conditional UI easy. They have costs. Each keystroke re-renders the component, and very large forms can feel slow.
An uncontrolled input, which keeps its value in the DOM, is reasonable when you only need the value on submit, or for file inputs (<input type="file"> is always uncontrolled because its value is read-only for scripts). You can read an uncontrolled field through a ref or through FormData when the form is submitted. The next chapter covers submission in detail.
Exercise
A developer writes <input value={text} /> with const [text, setText] = useState('hello'). The field shows "hello" but typing changes nothing. Why, and what are two ways to fix it?
Show answer
The input is controlled because it has a value prop, but nothing updates text, so React keeps resetting the field to "hello". Fix 1: add onChange={e => setText(e.target.value)}. Fix 2: use defaultValue="hello" to make it uncontrolled, or add readOnly if the field should never change.
Exercise
In the ContactForm example, what would happen if the handler were written as setForm({ [name]: value }) without spreading prev?
Show answer
Each change would replace the whole object with one that holds only the field just edited. The other fields would become undefined, which makes those inputs switch from controlled to uncontrolled and triggers a React warning.