Forms in React
Controlled vs uncontrolled inputs, form state, validation UX, and when native form submit is enough.
- react
- forms-in
Forms are where React state meets user intent. The core choice is controlled (React state is the source of truth for field values) versus uncontrolled (the DOM holds values until you read them). Most app UIs want controlled fields for validation and conditional UI; simple progressive-enhancement forms can stay closer to HTML.
Docs: Reacting to Input with State, <input>.
Controlled input
function LoginForm({ onSubmit }) {
const [email, setEmail] = useState('');
const [password, setPassword] = useState('');
const [error, setError] = useState(null);
function handleSubmit(e) {
e.preventDefault();
if (!email.includes('@')) {
setError('Enter a valid email');
return;
}
setError(null);
onSubmit({ email, password });
}
return (
<form onSubmit={handleSubmit} noValidate>
<label htmlFor="email">Email</label>
<input
id="email"
name="email"
type="email"
autoComplete="email"
value={email}
onChange={(e) => setEmail(e.target.value)}
/>
<label htmlFor="password">Password</label>
<input
id="password"
name="password"
type="password"
autoComplete="current-password"
value={password}
onChange={(e) => setPassword(e.target.value)}
/>
{error && <p role="alert">{error}</p>}
<button type="submit">Sign in</button>
</form>
);
}
Always pair label + id. Surface errors with role="alert" or aria-describedby. See useId for stable ids in reusable fields.
Uncontrolled + FormData
function SearchBox({ onSearch }) {
function handleSubmit(e) {
e.preventDefault();
const data = new FormData(e.currentTarget);
onSearch(String(data.get('q') ?? ''));
}
return (
<form onSubmit={handleSubmit}>
<input name="q" defaultValue="" aria-label="Search" />
<button type="submit">Go</button>
</form>
);
}
defaultValue sets initial DOM state; React does not drive each keystroke. Good for large free-text areas when you do not need per-keystroke React logic.
Object state for many fields
const [form, setForm] = useState({ name: '', company: '', role: '' });
const setField = (key) => (e) =>
setForm((f) => ({ ...f, [key]: e.target.value }));
Or useReducer when transitions include async submit states. Avoid derived state copies of server entities without a draft model.
Libraries and server actions
React Hook Form, Conform, and similar tools reduce re-renders and wire schema validation. In Next.js, Server Actions can receive FormData directly from progressive forms — still validate on the server.
Interview out-loud
“Controlled inputs keep value in React state for validation and conditional UI. Uncontrolled inputs use the DOM and FormData for simpler cases. I preventDefault on submit, associate labels, announce errors accessibly, and keep one source of truth for each field.”
Related on this site
- Multi-step Forms in React
- useId for Accessibility IDs
- useState Patterns
- Accessibility Patterns in React
Further reading
Edge cases worth rehearsing
Interviewers and production incidents cluster around the same edges: first render versus update, empty and loading states, Strict Mode double setup, concurrent interruptions, and what happens when identity (key, route params, user id) changes mid-edit. Walk one concrete user journey end-to-end — open, edit, navigate away, come back — and say which state survives.
Prefer fixing data flow and ownership before reaching for memoization or micro-optimizations. Prefer event handlers over effects when a user action is the trigger. Prefer deriving values during render over mirroring props into state. Prefer stable list keys from business ids. Measure with the profiler when performance is the claim.
When you cite an API, mention one failure mode: abort on unmount, serializable props across server/client boundaries, focus restoration for dialogs, or cache invalidation after a mutation. Specific beats generic every time.
Edge cases worth rehearsing
Interviewers and production incidents cluster around the same edges: first render versus update, empty and loading states, Strict Mode double setup, concurrent interruptions, and what happens when identity (key, route params, user id) changes mid-edit. Walk one concrete user journey end-to-end — open, edit, navigate away, come back — and say which state survives.
Prefer fixing data flow and ownership before reaching for memoization or micro-optimizations. Prefer event handlers over effects when a user action is the trigger. Prefer deriving values during render over mirroring props into state. Prefer stable list keys from business ids. Measure with the profiler when performance is the claim.
When you cite an API, mention one failure mode: abort on unmount, serializable props across server/client boundaries, focus restoration for dialogs, or cache invalidation after a mutation. Specific beats generic every time.
Related guides
- Accessibility Patterns in ReactPractical React a11y: labels, focus management, keyboard, live regions, and composition patterns that stay accessible.
- Avoid Prop Drilling with CompositionStop threading props through intermediates: children slots, inversion of control, and when context is the right escape hatch.
- Batching State UpdatesHow React 18+ batches setState in events, timeouts, and promises: when updates flush and why double setState still works.
- Children Prop PatternsUsing children and slot props for flexible APIs: wrappers, compound components, and when to prefer explicit props.
- Client Component BoundariesWhere to put use client: push interactivity to leaves, serializable props, and children as server slots.