
When working with forms in React, you’ll often come across two terms: controlled and uncontrolled components. Understanding the difference between them is essential for writing clean, predictable, and maintainable React applications.
In this blog post, I’ll break down the concept of controlled vs uncontrolled components in a simple, beginner-friendly way, with practical code examples to help you decide when to use which.
🧠 What Are Controlled Components?
- A controlled component is a form element (like
<input>
,<textarea>
,<select>
) whose value is controlled by React state.
✅ Characteristics:
- React state is the “single source of truth”
- Every keystroke updates state via
onChange
- Ideal when you want to validate input, show live previews, or enforce formats
- Used for complex form
- Rerenderer overhead
- Immediate validation.
💡 Example:
import React, { useState } from "react";
function ControlledForm() {
const [name, setName] = useState("");
const handleChange = (e) => {
setName(e.target.value);
};
const handleSubmit = (e) => {
e.preventDefault();
alert(`Submitted Name: ${name}`);
};
return (
<form onSubmit={handleSubmit}>
<label>
Name:
<input type="text" value={name} onChange={handleChange} />
</label>
<button type="submit">Submit</button>
</form>
);
}
🔍 How it works:
value={name}
binds the input value to React stateonChange
updates the state on every keystroke
🤖 What Are Uncontrolled Components?
An uncontrolled component is one where the form data is handled by the DOM itself. React doesn’t manage the input’s value directly — you access the value using ref
.
✅ Characteristics:
- You use
ref
to read values - No real-time state tracking
- Good for quick form handling or integrating with non-React code.
- Simple
- Quick
- Less control
💡 Example:
import React, { useRef } from "react";
function UncontrolledForm() {
const nameRef = useRef();
const handleSubmit = (e) => {
e.preventDefault();
alert(`Submitted Name: ${nameRef.current.value}`);
};
return (
<form onSubmit={handleSubmit}>
<label>
Name: <input type="text" ref={nameRef} />
</label>
<button type="submit">Submit</button>
</form>
);
}
🔍 How it works:
ref
gives direct access to the DOM element- You get the value when needed (not on every keystroke)
🎯 Conclusion
Controlled components give you full control over your form inputs via state, enabling things like validation, conditional rendering, and live feedback. On the other hand, uncontrolled components are simpler and rely on the browser’s default behavior, making them ideal for less interactive forms or quick scripts.
Understanding when and why to use each type helps you write more effective and optimized React code.
📌 keep building, and React on! ⚛️
Comments
Post a Comment