Controlled Inputs & Form State
A controlled input receives its displayed value from React state and reports changes through an event handler. This gives React a single source of truth and makes validation, conditional UI, and submission logic straightforward.
Controlled inputs are not automatically superior for every field. Very large forms can require careful optimization or specialized form libraries. The principle is to choose an ownership model deliberately rather than mixing uncontrolled DOM state and React state accidentally.
Checkboxes use checked rather than value for their boolean UI state.
Controlled input
function SearchBox() {
const [query, setQuery] = useState("");
return (
<input
value={query}
onChange={e => setQuery(e.target.value)}
aria-label="Search"
/>
);
}💡 The input's value is derived from React state, so every change flows through the component.
Key Takeaways
- Controlled inputs make form state explicit.
- Use
checkedfor controlled checkbox state. - Keep validation separate from presentation when forms become complex.