What Are Uncontrolled Components?
We've seen how controlled components let React manage form data. But sometimes you just need to grab the value from a form element without all that state management. That's where uncontrolled components come in. They're like letting the DOM handle things its own way.
Think of uncontrolled components as reading a value directly from the DOM when you need it. Instead of React controlling every keystroke, you just reach into the DOM and grab the current value whenever it's convenient for you.
Using Refs to Access Values
To create an uncontrolled component, you use a ref to access the form element's value. The ref gives you a direct reference to the DOM node, and you can read its value whenever you want. It's like having a key to the DOM's treasure chest.
The defaultValue prop sets the initial value, just like the value prop does for controlled components. But after that, the input manages itself. You only check the value when you need it, like when the user submits the form.
import { useRef } from "react";
function UncontrolledInput() {
const inputRef = useRef(null);
const handleSubmit = (e) => {
e.preventDefault();
alert("Name: " + inputRef.current.value);
};
return (
<form onSubmit={handleSubmit}>
<input type="text" ref={inputRef} defaultValue="John" />
<button type="submit">Submit</button>
</form>
);
}
Try it Yourself →
When to Use Uncontrolled Components
Uncontrolled components aren't just for old-school thinking. They shine in certain situations. If you're integrating with non-React code, or working with form libraries that manage their own state, uncontrolled components can be simpler.
They're also great for quick prototypes or when you just need to read values occasionally. If your form logic is simple and you don't need real-time validation, uncontrolled components can reduce your code significantly.
function FileInput() {
const fileRef = useRef(null);
const handleSubmit = (e) => {
e.preventDefault();
const file = fileRef.current.files[0];
console.log("Selected file:", file.name);
};
return (
<form onSubmit={handleSubmit}>
<input type="file" ref={fileRef} />
<button type="submit">Upload</button>
</form>
);
}
Try it Yourself →
Controlled vs Uncontrolled
So which should you choose? Controlled components give you more control (pun intended) over your form data. You can validate, transform, and react to changes instantly. They're the React way.
Uncontrolled components are simpler for quick tasks. They're like taking a snapshot of the DOM when you need it. For most React applications, controlled components are the way to go. But knowing both gives you flexibility to choose the right tool for each situation.