What is the difference between controlled and uncontrolled components in React?
· Category: React
Short answer
A controlled component stores its value in React state and updates via event handlers. An uncontrolled component lets the DOM manage its own value, which you can read using a ref.
Key differences
- Controlled: Value driven by state. Easy to validate, transform, and reset. Slightly more boilerplate.
- Uncontrolled: Value lives in the DOM. Less code for simple forms, but harder to synchronize or validate reactively.
Example
// Controlled
function ControlledInput() {
const [value, setValue] = useState('');
return <input value={value} onChange={(e) => setValue(e.target.value)} />;
}
// Uncontrolled
function UncontrolledInput() {
const inputRef = useRef(null);
const handleSubmit = () => {
alert(inputRef.current.value);
};
return <input ref={inputRef} defaultValue="hello" />;
}
When to use each
- Use controlled for forms that need real-time validation, formatting, or dependent fields.
- Use uncontrolled for file inputs, integrations with non-React libraries, or very simple one-off forms.