Part 03 / Topic 7 of 7
Controlled vs. uncontrolled inputs - an introduction
Section 3's GreetingForm input is what React calls controlled: it has both a value prop and an onChange handler, so React's own state is the single source of truth for what the input currently shows. examples/06_controlled_vs_uncontrolled.jsx names this pattern directly and puts an uncontrolled input right next to it:
// examples/06_controlled_vs_uncontrolled.jsx
export function PromoCodeControlled() {
const [code, setCode] = useState("");
return (
<div>
<input value={code} onChange={(event) => setCode(event.target.value.toUpperCase())} />
<p>React's own state for this field: {code || "(empty)"}</p>
</div>
);
}
export function PromoCodeUncontrolled() {
return (
<div>
<input defaultValue="" />
<p>React does not track this field's current value at all.</p>
</div>
);
}
PromoCodeUncontrolled's <input> has no value and no onChange at all - defaultValue only sets what the field starts with, once; after the first render, React never touches that field again. Typing "diwali10" into each field and reading both the input and the paragraph next to it really shows the difference (examples/06_controlled_vs_uncontrolled.test.jsx):
controlled: input shows "DIWALI10" (onChange upper-cased it)
paragraph shows "React's own state for this field: DIWALI10"
uncontrolled: input shows "diwali10" (the browser's own DOM node held it, untouched)
paragraph still shows "React does not track this field's current value at all."
The browser's own <input> DOM node really does hold "diwali10" in the uncontrolled case - typing works fine either way, from a user's point of view. The difference only shows up the moment application code wants to do something with the current value: a controlled input's value is always sitting right there in state, ready to read, validate, or send anywhere, mid-keystroke; an uncontrolled input's value lives only in the DOM, and reading it back into application code needs a tool this course has not introduced yet - defaultValue plus either a ref or FormData on submit, which is exactly where Part 5 ("Forms and controlled inputs") picks this up properly, including validation.
Done here? The practice set for Part 3 — including the solutions — is on the part page.