Topic 22 of 54
Uncontrolled Components
Overview
Sometimes you don't need React to track every single keystroke. Maybe you have a massive form and just want to read the values when the user clicks 'Submit'. An 'Uncontrolled Component' relies on the DOM itself to handle the form data. Instead of binding to state, you use a `ref` (via the `useRef` hook) to pull the value out of the DOM only when you actually need it.
Syntax
Notice there is no `useState` and no `onChange`. The input manages itself just like normal HTML. We only extract the data on submit.
Using useRef to read input
jsx
import { useRef } from 'react';
function UncontrolledForm() {
// Create a reference to attach to the input
const emailRef = useRef(null);
const handleSubmit = (e) => {
e.preventDefault();
// Read the value directly from the DOM node
const emailValue = emailRef.current.value;
alert(`Submitted: ${emailValue}`);
};
return (
<form onSubmit={handleSubmit}>
{/* Use 'defaultValue' instead of 'value' */}
<input
type="email"
ref={emailRef}
defaultValue="user@example.com"
/>
<button type="submit">Submit</button>
</form>
);
}Common Pitfalls
- Trying to use the `value` prop on an Uncontrolled component. If you aren't providing an `onChange` handler, you must use `defaultValue` instead.
Interview Tips
- When to use which? Use Controlled when you need instant validation, conditional submit buttons, or input masking. Use Uncontrolled (often with libraries like React Hook Form) for performance optimization on massive forms.
Real-World Example
File upload inputs (`<input type="file">`) are strictly Uncontrolled in React because their value is read-only and managed by the browser for security.
example
jsx
function FileUploader() {
const fileRef = useRef(null);
const handleUpload = () => {
const selectedFile = fileRef.current.files[0];
if (selectedFile) {
console.log("Uploading:", selectedFile.name);
// Upload logic...
}
};
return (
<div>
<input type="file" ref={fileRef} accept="image/*" />
<button onClick={handleUpload}>Upload</button>
</div>
);
}