Controlled vs Uncontrolled Components — React Technical Interview Questions & Answers
Controlled vs Uncontrolled Components
Controlled vs Uncontrolled Components
- Controlled: React state is the truth. Every keystroke goes through setState. Easy to validate, disable Submit, test. Uncontrolled: the DOM keeps the text. You read it via ref on submit (or defaultValue for initial). Less re-renders, less control.
- Most interview answers: prefer controlled for forms. Use uncontrolled for quick prototypes or heavy uncontrolled widgets (some date libraries). Don’t say one is ‘wrong’ — say which job fits.
- Controlled vs Uncontrolled Components — type hooks, submit → logs hooks. DOM kept the text. Controlled would use useState instead.
controlled: state → value
uncontrolled: DOM + refTechnical Interview Tip: Define both. Say when you’d still use a ref.
Code Examples for Controlled vs Uncontrolled Components
Example
// Uncontrolled
import { useRef } from "react";
export default function Search() {
const q = useRef(null);
function go(e) {
e.preventDefault();
console.log(q.current.value);
}
return (
<form onSubmit={go}>
<input ref={q} defaultValue="" />
<button>Find</button>
</form>
);
}
Controlled vs Uncontrolled Components — type hooks, submit → logs hooks. DOM kept the text. Controlled would use useState instead.
How to Explain Controlled vs Uncontrolled Components to an Interviewer
Which style do most React forms use?
Controlled