Controlled inputs
Overview
Form inputs have their own internal state in the browser: a text field remembers what you typed. In React you usually want your state to be in charge instead, so the UI always reflects your data. An input whose value comes from React state is called a controlled input.
A controlled text input
function NameField() {
const [name, setName] = useState('');
return (
<>
<input value={name} onChange={(e) => setName(e.target.value)} />
<p>Hello, {name || 'stranger'}!</p>
</>
);
}Every keystroke goes through a loop: the user types, onChange fires, you call setName, React re-renders, and the input displays the new name. Because your code sits in the middle of that loop, you can transform or validate the value as it’s typed:
// Force uppercase coupon codes, max 10 characters
<input
value={coupon}
onChange={(e) => setCoupon(e.target.value.toUpperCase().slice(0, 10))}
/>The read-only trap
If you pass value without onChange, React makes the input read-only — typing does nothing — and logs a warning: “You provided a value prop to a form field without an onChange handler.” Either add onChange, use readOnly deliberately, or use defaultValue (uncontrolled, below).
Other input types
Textarea
In React, <textarea> uses a value prop instead of children:
<textarea value={bio} onChange={(e) => setBio(e.target.value)} rows={4} />Checkbox
Checkboxes use checked and e.target.checked:
const [agreed, setAgreed] = useState(false);
<label>
<input type="checkbox" checked={agreed} onChange={(e) => setAgreed(e.target.checked)} />
I agree to the terms
</label>Select
<select> takes a value — no need for selected on options:
const [level, setLevel] = useState('beginner');
<select value={level} onChange={(e) => setLevel(e.target.value)}>
<option value="beginner">Beginner</option>
<option value="intermediate">Intermediate</option>
<option value="advanced">Advanced</option>
</select>For a multi-select, add multiple and pass an array: value={['a', 'b']}, reading the selection with Array.from(e.target.selectedOptions, (o) => o.value).
Radio buttons
A radio group is one piece of state; each radio is checked when its value matches:
const [plan, setPlan] = useState('monthly');
{['monthly', 'yearly'].map((option) => (
<label key={option}>
<input
type="radio"
name="plan"
value={option}
checked={plan === option}
onChange={(e) => setPlan(e.target.value)}
/>
{option}
</label>
))}Numbers
e.target.value is always a string, even for type="number". Convert it when you need a number, and be careful with the empty string while the user is mid-edit:
<input
type="number"
value={qty}
onChange={(e) => setQty(e.target.value === '' ? '' : Number(e.target.value))}
/>Many fields, one handler
Store the form in one object and use the input’s name to update the right field:
function SignupForm() {
const [form, setForm] = useState({ name: '', email: '', newsletter: true });
function handleChange(e) {
const { name, type, value, checked } = e.target;
setForm({ ...form, [name]: type === 'checkbox' ? checked : value });
}
return (
<form>
<input name="name" value={form.name} onChange={handleChange} />
<input name="email" type="email" value={form.email} onChange={handleChange} />
<label>
<input name="newsletter" type="checkbox" checked={form.newsletter} onChange={handleChange} />
Send me course updates
</label>
</form>
);
}Controlled must stay controlled
React warns when an input switches from uncontrolled to controlled: “A component is changing an uncontrolled input to be controlled.” This happens when value starts as undefined and later becomes a string:
const [user, setUser] = useState({}); // user.name is undefined at first
<input value={user.name} onChange={…} /> // ✗ starts uncontrolled
<input value={user.name ?? ''} onChange={…} /> // ✓ always a stringAlways initialise text state with '', never undefined or null.
Uncontrolled inputs
Not every input needs state. If you only need the values when the form is submitted, let the browser keep them and read them with FormData:
function ContactForm({ onSend }) {
function handleSubmit(e) {
e.preventDefault();
const data = Object.fromEntries(new FormData(e.currentTarget));
onSend(data); // { name: '…', message: '…' }
e.currentTarget.reset();
}
return (
<form onSubmit={handleSubmit}>
<input name="name" defaultValue="" required />
<textarea name="message" defaultValue="" required />
<button type="submit">Send</button>
</form>
);
}Use defaultValue (or defaultChecked) to set the initial value of an uncontrolled input.
| Use controlled inputs when… | Uncontrolled is fine when… |
|---|---|
| the UI reacts as the user types (live search, character counters) | you only need values on submit |
| you validate or format on each keystroke | the browser’s built-in validation is enough |
| other components depend on the value | the form is simple and self-contained |
| you need to reset or set values from code | — |
React 19’s form actions build on uncontrolled forms and FormData — that’s the next lesson.
Performance note: a controlled input re-renders its component on every keystroke. That’s normally instant. If a big list below the input re-renders slowly as you type, see Transitions and deferred values.
A course filter form
Build CourseFilters({ onChange }) with controlled inputs: a text search, a <select> for level (All, Beginner, Intermediate, Advanced), a “Free only” checkbox, and radio buttons for sort order (title or newest). Keep all values in one state object, and call onChange(filters) with the new filters every time one changes. Add a “Reset” button that restores the defaults.
import { useState } from 'react';
const defaults = { q: '', level: 'all', freeOnly: false, sort: 'title' };
export function CourseFilters({ onChange }) {
// your code here
}import { useState } from 'react';
const defaults = { q: '', level: 'all', freeOnly: false, sort: 'title' };
export function CourseFilters({ onChange }) {
const [filters, setFilters] = useState(defaults);
function update(next) {
setFilters(next);
onChange(next);
}
function handleChange(e) {
const { name, type, value, checked } = e.target;
update({ ...filters, [name]: type === 'checkbox' ? checked : value });
}
return (
<form onSubmit={(e) => e.preventDefault()}>
<input name="q" aria-label="Search" value={filters.q} onChange={handleChange} />
<select name="level" aria-label="Level" value={filters.level} onChange={handleChange}>
<option value="all">All levels</option>
<option value="beginner">Beginner</option>
<option value="intermediate">Intermediate</option>
<option value="advanced">Advanced</option>
</select>
<label>
<input type="checkbox" name="freeOnly" checked={filters.freeOnly} onChange={handleChange} />
Free only
</label>
<fieldset>
<legend>Sort by</legend>
{['title', 'newest'].map((option) => (
<label key={option}>
<input
type="radio"
name="sort"
value={option}
checked={filters.sort === option}
onChange={handleChange}
/>
{option === 'title' ? 'Title' : 'Newest'}
</label>
))}
</fieldset>
<button type="button" onClick={() => update(defaults)}>Reset</button>
</form>
);
}Summary
- A controlled input gets its
value(orchecked) from state and updates that state inonChange. - If you pass
valuewithoutonChange, the input becomes read-only and React warns. - Checkboxes use
checked; selects and textareas usevalue; radio groups comparechecked={state === option}. - Never switch an input between controlled and uncontrolled — don’t let
valuebecomeundefined. - Uncontrolled inputs (with
defaultValueandFormData) are simpler when you only need the values on submit.