In React, form elements can be either controlled or uncontrolled, depending on whether React manages their state.
1️⃣ Controlled Component
- React state controls the form input value.
- Input changes are handled via
onChangeand state updates. - Ensures single source of truth.
Example:
import React, { useState } from "react";
function ControlledForm() {
const [name, setName] = useState("");
const handleSubmit = (e) => {
e.preventDefault();
alert(`Name: ${name}`);
};
return (
<form onSubmit={handleSubmit}>
<input
type="text"
value={name} // controlled by state
onChange={(e) => setName(e.target.value)}
/>
<button type="submit">Submit</button>
</form>
);
}
Key Points:
- Value comes from state (
value={name}) - Updates go through
onChange - Easy to validate, reset, or manipulate input programmatically
2️⃣ Uncontrolled Component
- Input value is managed by the DOM, not React state.
- Use
refto access input values when needed.
Example:
import React, { useRef } from "react";
function UncontrolledForm() {
const nameRef = useRef();
const handleSubmit = (e) => {
e.preventDefault();
alert(`Name: ${nameRef.current.value}`);
};
return (
<form onSubmit={handleSubmit}>
<input type="text" ref={nameRef} /> {/* value not controlled */}
<button type="submit">Submit</button>
</form>
);
}
Key Points:
- Input manages its own state in the DOM
- Accessed via
ref - Less code for simple forms but harder to validate or manipulate dynamically
Comparison
| Feature | Controlled Component | Uncontrolled Component |
|---|---|---|
| Value managed by | React state | DOM |
| Access value | state variable |
ref.current.value |
| Validation | Easy | Harder |
| Use case | Complex forms, validation | Simple forms, quick input |
⚡ In short:
Controlled components let React manage form state, giving full control, while uncontrolled components rely on the DOM for state, making them simpler but less flexible.