What is the difference between a controlled and uncontrolled component?
Hint
Controlled = React owns the value; uncontrolled = DOM owns it (accessed via ref)
Full Answer
Controlled component — React state is the single source of truth. Every change goes through setState.
Uncontrolled component — the DOM stores the value. You pull it with a ref when needed.
// Controlled — React owns the value
function Controlled() {
const [value, setValue] = useState('');
return (
<input
value={value}
onChange={e => setValue(e.target.value)}
/>
);
}
// Uncontrolled — DOM owns the value
function Uncontrolled() {
const inputRef = useRef(null);
function handleSubmit() {
console.log(inputRef.current.value); // pull on demand
}
return <input ref={inputRef} defaultValue="initial" />;
}
When to use each:
- Controlled — instant validation, conditional disabling, dynamic inputs, format-on-type
- Uncontrolled — file inputs (always uncontrolled), integrating with non-React code, simple one-off forms where you only need value on submit
💡 React recommends controlled components for most cases. File inputs (
<input type="file">) are always uncontrolled — you can't set their value programmatically for security reasons.More React Fundamentals Questions
Practice this in a timed sprint
5 free questions, no signup required