🧠 1. What is a Controlled Component?
In a controlled component, React controls the input value via useState.
The form input’s value is bound to component state.
🔤 Example:
import { useState } from "react";
function ControlledForm() {
const [name, setName] = useState("");
const handleSubmit = (e) => {
e.preventDefault();
alertSubmitted: ${name}
);
};
return (
<form onSubmit={handleSubmit}>
<input
type="text"
value={name}
onChange={(e) => setName(e.target.value)}
/>
<button type="submit">Submit</button>
</form>
);
}
💡 Key Points:
value is controlled by useState.
Input changes update state via onChange.
Good for validation, dynamic behavior, etc.
🧩 2. What is an Uncontrolled Component?
In uncontrolled components, the DOM maintains the input value.
You use ref to access the input value when needed.
🔤 Example:
import { useRef } from "react";
function UncontrolledForm() {
const inputRef = useRef();
const handleSubmit = (e) => {
e.preventDefault();
alertSubmitted: ${inputRef.current.value}
);
};
return (
<form onSubmit={handleSubmit}>
<input type="text" ref={inputRef} />
<button type="submit">Submit</button>
</form>
);
}
💡 Key Points:
No state management.
Simple and quick for one-time input collection.
Less control over validation and UI feedback.
🔍 3. When to Use What?
Use Case
Use Controlled
Use Uncontrolled
Real-time validation
✅ Yes
❌ No
Instant UI updates (e.g., filters)
✅ Yes
❌ No
Simple one-time data grab
❌ Not necessary
✅ Yes
Working with 3rd party non-React forms
❌ Not ideal
✅ Often better
✅ Summary
Controlled = React state handles everything. More power, more code.
Uncontrolled = DOM handles the value. Simpler but limited.
Best Practice: Use controlled components for most dynamic forms in React.