Lesson 12 of 80
Should React state or the DOM itself be the source of truth for an input's value? Two legitimate answers, and mixing them is where the bugs live.
12 min read
Every option explains itself — why the right one is right, and why each wrong one is wrong. Miss one and it comes back later on a spaced-repetition schedule.
Question 1 of 2
An input has `value={state.value}` but no `onChange` handler. What happens when the user tries to type?
Hints without spoilers, and a plain explanation of why a wrong answer was wrong — answered only from this lesson. Free account, no card.
Sign up freeWhat interviewers actually ask about this, and what a strong answer has to cover.
A strong answer covers
Likely follow-ups
A controlled input's value is driven entirely by React state — the DOM element never has a mind of its own:
function ControlledInput() {
const [value, setValue] = useState("");
return <input value={value} onChange={(e) => setValue(e.target.value)} />;
}
Every keystroke fires onChange, which updates state, which re-renders the input with the new value — React is the single source of truth, and the DOM just reflects it.
An uncontrolled input lets the DOM manage its own value; React only reaches in when it needs to, via a ref:
function UncontrolledInput() {
const inputRef = useRef(null);
function handleSubmit() {
console.log(inputRef.current.value); // read only when needed
}
return <input ref={inputRef} defaultValue="" />;
}
<input value={value} onChange={...} /> — React state IS the source of truth for what's on screen.
| | Controlled | Uncontrolled | |---|---|---| | Source of truth | React state | The DOM | | Validate/format as you type | Easy — you see every keystroke | Harder — need to read the DOM | | Performance on huge forms | A re-render per keystroke | No re-render per keystroke | | Simple "read on submit" forms | Overkill | A natural fit |
value flips between undefined and a real string across renders (e.g., from state.value before data loads), React logs a warning about switching between controlled and uncontrolled — pick one mode and stay in it, using value ?? "" if needed.<canvas>-based editor) that already manage their own internal state — fighting them into fully controlled inputs is often more trouble than it's worth."Build a form" exercises almost always reveal whether a candidate defaults to controlled inputs out of habit or genuinely understands the tradeoff — and the controlled/uncontrolled switching warning is a real bug interviewers like to plant deliberately.