Q16: What is the difference between Controlled and Uncontrolled Components?
- Controlled Component: Form input state is driven by React state (
value+onChange). React acts as the 'single source of truth'. - Uncontrolled Component: Form input state is handled directly by the browser DOM. React reads input values imperatively using a
useRefpointer.
Controlled vs Uncontrolled Forms
// Controlled
const [val, setVal] = useState('');
<input value={val} onChange={e => setVal(e.target.value)} />
// Uncontrolled
const inputRef = useRef();
<input ref={inputRef} defaultValue="Initial" />💡 Controlled inputs store text inside React state; uncontrolled inputs leave data storage to the DOM element.
Key Takeaways
- Controlled components provide instant validation and dynamic input control.
- Uncontrolled components offer simpler integration for heavy file inputs or legacy forms.
Knowledge Check
Which form input type in HTML is always inherently an Uncontrolled Component in React?