ποΈ Controlled vs Uncontrolled Components
In React, form inputs can be either controlled or uncontrolled. Understanding the difference is key to building reliable and scalable forms.
β Controlled Components
Controlled components have their state fully managed by React. Input values are linked to state variables, and changes are handled through events.
function ControlledInput() {
const [name, setName] = React.useState("");
const handleChange = (e) => setName(e.target.value);
return (
<input type="text" value={name} onChange={handleChange} />
);
}
- β React has full control of the value
- β Enables validation, conditional logic, etc.
- β οΈ Requires more code and state management
πΉοΈ Uncontrolled Components
Uncontrolled components rely on the DOM to manage their values using a ref
. React doesnβt track the input's state directly.
function UncontrolledInput() {
const inputRef = React.useRef();
const handleSubmit = () => {
alert("Input value: " + inputRef.current.value);
};
return (
<>
<input type="text" ref={inputRef} />
<button onClick={handleSubmit}>Submit</button>
</>
);
}
- β Less code, simpler in small forms
- β οΈ Harder to validate or manipulate programmatically
- β οΈ Doesnβt reflect state in Reactβs data flow
π When to Use Each
- Use Controlled: When you need validation, conditional logic, or dynamic updates.
- Use Uncontrolled: For simple forms or when integrating with non-React libraries.
Aspect | Controlled | Uncontrolled |
---|---|---|
State | Managed by React | Managed by DOM |
Validation | Easier | Harder |
Code Complexity | Higher | Lower |
Refs Required | No | Yes |
Controlled components are the preferred approach in React apps due to their flexibility and integration with the React state model. Uncontrolled components can be useful in isolated, simple use cases.