Controlled components have React state as source of truth. Uncontrolled components use DOM as source of truth.
Controlled:
1function ControlledInput() {2 const [value, setValue] = useState("");34 return (5 <input6 value={value}7 onChange={e => setValue(e.target.value)}8 />9 );10}
Uncontrolled:
1function UncontrolledInput() {2 const inputRef = useRef<HTMLInputElement>(null);34 const handleSubmit = () => {5 console.log(inputRef.current?.value);6 };78 return (9 <>10 <input ref={inputRef} defaultValue="" />11 <button onClick={handleSubmit}>Submit</button>12 </>13 );14}
Key differences: | Feature | Controlled | Uncontrolled | |---------|------------|--------------| | Value source | React state | DOM | | Updates | Via setState | Via ref | | Instant validation | Yes | No | | Dynamic input | Easy | Hard | | Code complexity | More | Less |
When to use controlled:
When to use uncontrolled: