Controlled inputs
🏠The everyday picture
A bank form filled in by a clerk who repeats every word back to you as they write it. The form always shows exactly what the clerk has recorded.
📘What it really is
- A controlled input takes its value from state and updates state on every change:
const [query, setQuery] = useState("");
<label htmlFor="search">Search enquiries</label>
<input
id="search"
value={query}
onChange={event => setQuery(event.target.value)}
/>
-
State is now the single source of truth for the input. You can use it anywhere: filtering, validation, clearing it with
setQuery(""). -
The same pattern works for
<textarea>and<select>; checkboxes usecheckedandevent.target.checked. - Typing a letter re-renders the component. That's normal and fast.
- Filtering with search text is a calculation while rendering:
const visible = enquiries.filter(e =>
e.name.toLowerCase().includes(query.trim().toLowerCase()));
🖱️Try it
Add a search box above the panels that filters enquiries by name or subject, and a <select> to filter by status
("all", "new", "in-progress", "closed"). Both should be controlled. Add a "Clear" button that resets both.
✅Quick check
In a controlled input, where does the input's displayed value come from?
Show the answer
From state, which is updated on every change.
How do you clear a controlled input from a button?
Show the answer
Set its state back to an empty string.
