21. What is the difference between controlled and uncontrolled components?
Feature | Controlled Component | Uncontrolled Component |
|---|---|---|
Form Data Location | Stored in React state | Stored in the DOM |
Value Control | React controls the input value | DOM controls the input value |
Data Access | Through state variables | Through refs |
Validation | Easier to validate and update | More manual handling |
Recommended | Yes, for most forms | Useful for simple cases or integrations |
Controlled Component
function Form() {
const [name, setName] = React.useState("");
return (
<input
value={name}
onChange={(e) => setName(e.target.value)}
/>
);
}Uncontrolled Component
function Form() {
const inputRef = React.useRef();
const handleSubmit = () => {
console.log(inputRef.current.value);
};
return (
<>
<input ref={inputRef} />
<button onClick={handleSubmit}>Submit</button>
</>
);
}Summary
Controlled components keep form data in React state, making them easier to manage and validate. Uncontrolled components keep data in the DOM and are accessed using refs.