Controlled vs Uncontrolled Components in React:
1. Controlled Component
- Form inputs are controlled by React state.
- The value of the input comes from state.
- Any change in input updates the state, and state updates the UI.
- React is the “single source of truth”.
✅ Example (Controlled Input):
import React, { useState } from "react";
function ControlledExample() {
const [name, setName] = useState("");
const handleSubmit = (e) => {
e.preventDefault();
console.log("Submitted Name:", name);
};
return (
<form onSubmit={handleSubmit}>
<input
type="text"
value={name} // ✅ value comes from state
onChange={(e) => setName(e.target.value)} // ✅ state updates
/>
<button type="submit">Submit</button>
</form>
);
}
export default ControlledExample;
👉 Input value is always synced with state.
2. Uncontrolled Component
- Form inputs are not controlled by React state.
- The value of the input is stored directly in the DOM.
- We use Refs to access the input value when needed.
✅ Example (Uncontrolled Input):
import React, { useRef } from "react";
function UncontrolledExample() {
const nameRef = useRef();
const handleSubmit = (e) => {
e.preventDefault();
console.log("Submitted Name:", nameRef.current.value); // ✅ access directly from DOM
};
return (
<form onSubmit={handleSubmit}>
<input type="text" ref={nameRef} /> {/* value not controlled by state */}
<button type="submit">Submit</button>
</form>
);
}
export default UncontrolledExample;
👉 React does not control the value, it’s managed by the DOM.
🔹 Difference Between Controlled & Uncontrolled
| Feature | Controlled Component ✅ | Uncontrolled Component ❌ |
|---|---|---|
| Data stored in | React State | DOM (via ref) |
| Value updated by | setState / useState |
Direct user input |
| Easier to validate? | Yes (state is accessible) | Harder (need refs) |
| React is source of truth? | ✅ Yes | ❌ No |
| Example use cases | Forms with validation, dynamic UIs | Simple forms, quick inputs |
🔹 MERN Use Case
- Controlled components → Best for forms where you need real-time validation (e.g., login/signup in React).
- Uncontrolled components → Useful when integrating with third-party libraries (e.g., file uploads where you just need the final value).