React / 59
Controlled vs uncontrolled components
Who owns the value, React state or the component itself? Controlled inputs and components take their value from props or state, uncontrolled ones keep their own.
Two owners, side by side
Type in both boxes
Try itUncontrolled
<input defaultValue="Asha" ref={inputRef} />
React knows: nothing yet
Controlled
<input value={name} onChange={…} />
React knows: "Asha"
- Uncontrolled: the DOM keeps the value. React gives it a starting value and reads it only when asked.
- Controlled: React state holds the value. The input just displays it, and every keystroke goes through your
onChange.
Uncontrolled: defaultValue and read later
export default function NewsletterForm() {
function handleSubmit(e) {
e.preventDefault();
const data = new FormData(e.currentTarget);
alert(`Subscribed: ${data.get("email")}`);
}
return (
<form onSubmit={handleSubmit}>
<input name="email" type="email" defaultValue="" required />
<button type="submit">Subscribe</button>
</form>
);
}Less code, no re-render per keystroke. Great for simple forms you only read on submit. (React 19's <form action={fn}> also hands your function the FormData.)
Controlled: value + onChange
import { useState } from "react";
export default function DishSearch() {
const [query, setQuery] = useState("");
return (
<div>
<input
value={query}
onChange={(e) => setQuery(e.target.value.slice(0, 30))}
placeholder="Search dishes"
/>
<p>{query.length} / 30</p>
<button type="button" onClick={() => setQuery("")} disabled={!query}>
Clear
</button>
</div>
);
}React always knows query, so it can limit the length, show a counter, clear the box, or filter a list as you type.
| You need… | Use |
|---|---|
| The value only on submit | Uncontrolled |
| Live validation, counters, formatting | Controlled |
| To reset or change it from code | Controlled |
| Another component to react to it | Controlled (and lift the state) |
The same idea for your own components
"Controlled" isn't only about inputs. Any component is uncontrolled if it keeps its important state inside, and controlled if that state comes in through props:
import { useState } from "react";
function MenuSection({ title, children }) {
const [isOpen, setIsOpen] = useState(false); // it decides
return (
<section>
<button onClick={() => setIsOpen(!isOpen)}>{title}</button>
{isOpen && children}
</section>
);
}function MenuSection({ title, children, isOpen, onToggle }) {
// the parent decides
return (
<section>
<button onClick={onToggle}>{title}</button>
{isOpen && children}
</section>
);
}The uncontrolled one is easy to drop in, but nobody outside can open or close it. The controlled one needs a parent to manage it, but the parent can then coordinate many sections. That's exactly what the next topic does.
Gotchas
Recall
Can you answer these?
0/4
Answer out loud (or in your head) before you tap. That's what makes it stick.
Saved on this device only. No login.
