Controlled vs Uncontrolled components
Controlled Component
The field value is stored in React state. React fully controls the form.
tsx
function ControlledInput() {
const [value, setValue] = useState('');
return (
<input
value={value}
onChange={(e) => setValue(e.target.value)}
/>
);
}Uncontrolled Component
The value is stored in the DOM. Read via ref.
tsx
function UncontrolledInput() {
const ref = useRef<HTMLInputElement>(null);
const handleSubmit = () => {
console.log(ref.current?.value);
};
return <input ref={ref} defaultValue="default" />;
}When to use which
| Controlled | Uncontrolled | |
|---|---|---|
| Live validation | Yes | No |
| Dependent fields | Yes | No |
| Simple forms | Overkill | Yes |
| Non-React integration | Hard | Yes |
Most React forms are controlled. Uncontrolled is used for file inputs and integration with third-party DOM libraries.
updated
did you know it?