Controlled and Uncontrolled Components in React
In React when working with forms there are two approaches to managing field values: controlled and uncontrolled components.
Controlled Component
This is a component where form value is stored in React component state, and any user input change happens through onChange and state update.
Example:
import { useState } from "react";
function ControlledInput() {
const [value, setValue] = useState("");
return (
<input
type="text"
value={value}
onChange={(e) => setValue(e.target.value)}
/>
);
}
Here:
valueis managed through React state- React knows actual value at any moment
- Can validate/update data on the fly
Uncontrolled Component
This is a component where value isn't stored in React state but is extracted directly from DOM using ref.
Example
import { useRef } from "react";
function UncontrolledInput() {
const inputRef = useRef();
const handleSubmit = () => {
alert(inputRef.current.value);
};
return (
<>
<input type="text" ref={inputRef} />
<button onClick={handleSubmit}>Submit</button>
</>
);
}
Here:
- React doesn't know what value
inputhas right now - Value is obtained only when needed
- Simple to implement, especially if need access to value once
Comparison Table
| Controlled component | Uncontrolled component | |
|---|---|---|
| Where value stored | In React state | In DOM via ref |
| React "knows" value? | Yes | No |
| Suitable for validation | Excellent fit | Harder to implement |
| Performance | May re-render more often | Faster for large forms |
| Implementation simplicity | Slightly more complex | Simpler in simple scenarios |
When to Use?
Controlled:
- If need to validate input in real time
- For complex forms
- When full control is important
Uncontrolled:
- Simple forms or fields
- When value needed only on submit
- Integration with third-party libraries
Tip:
Use controlled components when you need to control state and do validation. For simple forms or integration with formData uncontrolled are better fit.