TechnicalMedium React
What is the difference between controlled and uncontrolled components in React?
Asked for Frontend Developer, Full-Stack Developer
Why they ask this: Forms are in every app; this shows how you handle user input and validation.
Answer
- Controlled: React state is the single source of truth. The input's
valuecomes from state and every change goes throughonChange. - Uncontrolled: the DOM keeps the value. You read it when needed with a
refor from the form data on submit.
jsx
// Controlled
const [email, setEmail] = useState('');
<input value={email} onChange={(e) => setEmail(e.target.value)} />
// Uncontrolled
const inputRef = useRef(null);
<input ref={inputRef} defaultValue="" />
// later: inputRef.current.valueChoose controlled inputs for instant validation, formatting or conditional UI. Uncontrolled inputs are simpler for basic forms and file inputs (<input type="file"> is always uncontrolled). Form libraries such as React Hook Form mostly use uncontrolled inputs for performance.
Can you explain this in your own words?