What are Uncontrolled Components?
In an uncontrolled component, the form data is handled by the DOM itself, rather than by a React component's state. Instead of writing an event handler for every state update, you use a ref to pull the values from the DOM when you need them (e.g., when the form is submitted).
Basic Implementation with useRef
To create an uncontrolled component, you use the useRef hook to create a reference to the DOM element and access its .value property directly.
Initial Values (defaultValue)
In the React rendering lifecycle, the value attribute on form elements overrides the value in the DOM. With uncontrolled components, you often want React to specify the initial value, but leave subsequent updates uncontrolled. For this, use defaultValue instead of value.
When to Use Uncontrolled Components
- File Inputs: The
<input type="file">is always uncontrolled in React because its value is read-only from a script perspective. - Simple Forms: When you don't need instant validation or custom UI feedback while the user types.
- Non-React Integration: When integrating with third-party DOM libraries (like jQuery plugins) that manage their own internal state.
- Performance: In extremely large forms where state updates on every keystroke might cause lag (though
useMemoor React Hook Form are usually better solutions here).
Controlled vs. Uncontrolled
| Feature | Controlled | Uncontrolled |
|---|---|---|
| Source of Truth | React State | DOM |
| Value Access | Immediate (on change) | On demand (via ref) |
| Instant Validation | Easy | Difficult |
| Boilerplate | Higher | Lower |
| File Upload Support | No | Yes |