Beginner LevelReact JS & React 19
What is the difference between Controlled and Uncontrolled components in React forms?
❓ Interview Prompt: Compare Controlled components (React state driven) vs Uncontrolled components (DOM ref driven with defaultValue).
1. Controlled Components (Recommended):
Form input values are driven entirely by React state ('value={state}' + 'onChange={e => setState(e.target.value)}').
•
Provides real-time validation, dynamic disabling, and conditional formatting.
2. Uncontrolled Components:
Form data is handled by the DOM directly. Values are read using 'useRef' or native 'FormData' on submit ('defaultValue="Alice"').
•
Ideal for simple forms, file inputs ('<input type="file" />'), or integrating with non-React libraries.
Code Implementation Example
jsx
// Controlled Component (React manages state)
function ControlledInput() {
const [name, setName] = useState('');
return <input value={name} onChange={e => setName(e.target.value)} />;
}
// Uncontrolled Component (DOM manages value via ref/FormData)
function UncontrolledInput() {
const inputRef = useRef();
const handleSubmit = (e) => {
e.preventDefault();
alert(inputRef.current.value); // Read directly from DOM
};
return (
<form onSubmit={handleSubmit}>
<input ref={inputRef} defaultValue="Initial" />
<button type="submit">Submit</button>
</form>
);
}💡Controlled vs Uncontrolled form input patterns.
🎯 Interview Key Takeaway
Controlled components store form state in React for real-time validation; uncontrolled components rely on DOM refs.
#Forms#Controlled Components#Uncontrolled Components#Beginner
Back to all React JS & React 19 Questions→