Controlled components — React controls the element form value 💼 Uncontrolled components — DOM controls the element form value 🆓
// Controlled — value through state
<input value={value} onChange={handleChange} />
// Uncontrolled — value directly from DOM
<input defaultValue="text" ref={inputRef} />Controlled and uncontrolled components — like the difference between a trained and a wild horse! 🐎
Controlled components — like manual mode in a video game: you control everything yourself:
function ControlledForm() {
const [name, setName] = useState('');
return (
<input
value={name}
onChange={(e) => setName(e.target.value)}
/>
);
}How it works:
Uncontrolled components — like autopilot: browser controls itself, you just observe:
function UncontrolledForm() {
const inputRef = useRef();
return <input defaultValue="initial value" ref={inputRef} />;
}How it works:
// ✅ Forms with validation
// ✅ Instant checking
// ✅ Complex interactions
// ✅ Testing
<input value={email} onChange={handleEmailChange} />// ✅ Simple forms
// ✅ Integration with non-React code
// ✅ When no real-time control needed
<input defaultValue={name} ref={nameRef} />// Full control
const [text, setText] = useState('');
// Can check every character
const handleChange = (e) => {
const value = e.target.value;
// Check: only letters
if (/^[a-zA-Z]*$/.test(value)) {
setText(value);
}
};
<input value={text} onChange={handleChange} />// Minimal code
const inputRef = useRef();
// Get value only on submit
const handleSubmit = () => {
console.log(inputRef.current.value);
};
<input defaultValue="text" ref={inputRef} />// ❌ Mistake — mixing value and defaultValue
<input value={name} defaultValue="text" /> // Conflict!
// ✅ Correct — choose one approach
<input value={name} onChange={handleChange} /> // Controlled
// or
<input defaultValue={name} ref={inputRef} /> // Uncontrolled// ❌ Mistake — trying to get uncontrolled component value
function Form() {
// No ref!
return <input defaultValue="text" />;
// How to get value? Impossible!
}
// ✅ Correct — use ref
function Form() {
const inputRef = useRef();
return <input defaultValue="text" ref={inputRef} />;
}Understanding the difference between controlled and uncontrolled components helps build forms correctly in React! 💪
Want more articles to prepare for interviews? Subscribe to EasyAdvice, bookmark the site and improve yourself every day 💪