HomeReact
Chapter 5
05 — Forms & Controlled Components
Forms are how users input data in web apps. React forms differ from HTML forms — you typically control every input with state (a "controlled component").
Controlled vs Uncontrolled
| Aspect | Controlled | Uncontrolled |
|---|---|---|
| State managed by | React (useState) | DOM itself |
| Access value via | State variable | ref (useRef) |
| Re-renders | On every keystroke | None |
| Validation | Instant (per keystroke) | On submit |
| When to use | Most cases ✅ | File inputs, third-party libs |
Common Form Elements
| Element | Value Prop | Event |
|---|---|---|
<input type="text"> | value | onChange |
<textarea> | value | onChange |
<select> | value | onChange |
<input type="checkbox"> | checked | onChange |
<input type="radio"> | checked | onChange |
<input type="file"> | N/A (uncontrolled) | onChange |
Validation Strategies
| Strategy | Timing | Pros | Cons |
|---|---|---|---|
| On change | Every keystroke | Instant feedback | Can feel aggressive |
| On blur | When field loses focus | Good UX balance | Delayed feedback |
| On submit | Form submission | Simplest | User waits |
| Hybrid | Blur first, then change | Best UX | More code |
Libraries for Complex Forms
- React Hook Form — performant (minimal re-renders), great DX
- Formik — popular, pairs well with Yup validation
- Zod + react-hook-form — type-safe schema validation
File
forms.tsx— controlled inputs, multi-field forms, validation, checkbox/radio, select, file upload, form patterns