Controlled vs Uncontrolled Components with useRef
Controlled vs Uncontrolled Components with useRef
1. Two Philosophical Approaches to Form Inputs
In web development, form elements like <input>, <textarea>, and <select> maintain their own internal state inside the browser's Document Object Model as users type.
React offers two primary architectural patterns to handle form inputs:
- 1Controlled Components: React state (
useState) is the single source of truth. Every input value is pushed into state viaonChange, and read from state viavalue. - 2Uncontrolled Components: The browser DOM itself holds the source of truth. React reads values only when needed (such as upon form submission) using a
useRefreference.
2. Implementing Controlled Components
Why use Controlled Components?
- Instant Validation: Validate input on every keystroke (e.g. enforcing password rules or phone formatting).
- Dynamic UI Responses: Enable or disable submit buttons based on current field values.
- Enforcing Input Formats: Convert text to uppercase automatically as the user types.
3. Implementing Uncontrolled Components with useRef
When you don't need real-time keystroke tracking and want to maximize performance in massive forms, useRef provides direct access to the underlying DOM node:
4. Special Case: HTML File Inputs <input type="file" />
In HTML, file inputs are strictly read-only for JavaScript security reasons (scripts cannot programmatically set a user's file path).
Because their value cannot be set via value={...}, file inputs in React must always be uncontrolled components accessed via useRef!
Practice Quiz
<input type="file" /> elements always be treated as uncontrolled in React?Multi-Input Forms with Dynamic State Handlers
Continue learning with hands-on practice, examples, and exercises in the upcoming topic.
Related Lessons
| Previous Lesson | Next Lesson |
|---|---|
| Lifecycle Equivalents: Mount, Update, and Unmount | Multi-Input Forms with Dynamic State Handlers |
Practice Quiz
Test your understanding of this lesson with 5 questions. Each question has one correct answer.