📌 Introduction
In React, there are two main ways to manage form inputs: controlled and uncontrolled components. Controlled components rely on React state to store and update form data, while uncontrolled components depend on the DOM to handle their state. Knowing the difference helps you choose the most efficient approach for your project.
🎯 Controlled Components
A controlled component is a form element whose value is controlled by React through its state. Every time a user types or interacts with the input, an onChange event updates the state, and the state determines the displayed value.
In controlled components, the form data flows in one direction, from the component’s state to the form field. This makes it easy to perform validations, enforce formatting, and respond immediately to user input.
Example
function ControlledForm() {
const [name, setName] = React.useState("");
return (
<form>
<input
type="text"
value={name}
onChange={(e) => setName(e.target.value)}
/>
<p>Typed name: {name}</p>
</form>
);
}
Advantages
- Full control over input values.
- Easy validation and formatting.
- Synchronization with other UI elements.
Drawbacks
- Requires more code.
- May cause performance overhead with many inputs.
🪄 Uncontrolled Components
An uncontrolled component keeps its own state inside the DOM. You don’t manage it through React state; instead, you access the value directly using refs.
In uncontrolled components, React doesn’t track input changes directly. The DOM holds the data, and you retrieve it only when needed, such as during form submission.
Example
function UncontrolledForm() {
const nameRef = React.useRef();
const handleSubmit = (e) => {
e.preventDefault();
alert(`Name: ${nameRef.current.value}`);
};
return (
<form onSubmit={handleSubmit}>
<input type="text" ref={nameRef} />
<button type="submit">Submit</button>
</form>
);
}
Advantages
- Less code for simple forms.
- Slightly better performance for small, static forms.
Drawbacks
- Harder to validate dynamically.
- No real-time synchronization with UI state.
⚖️ Controlled vs Uncontrolled Components
Feature |
Controlled Components |
Uncontrolled Components |
Data Source |
React state |
DOM |
Real-time Validation |
Easy |
Difficult |
Code Complexity |
Higher |
Lower |
Performance |
May be slower |
Faster for small forms |
Best Use Case |
Complex, dynamic forms |
Simple, static forms |
📝 Summary
Controlled and uncontrolled components are two different ways of handling form inputs in React. Controlled components give you full control, making them ideal for complex forms with validation and real-time feedback. Uncontrolled components are simpler and faster for small, static forms where live validation isn’t needed. Choosing the right approach depends on your project’s complexity, performance requirements, and the amount of form interactivity you need.