Forms and Validation
Controlled components
In a controlled component, React state is the single source of truth for the input's current value. Every keystroke fires onChange, updates state, and re-renders the input with the new value. This makes it straightforward to format input, enforce constraints, or disable submission when required fields are empty. Always pair inputs with an explicit <label htmlFor="..."> so screen readers announce the field:
import { useState } from "react";
function NewsletterForm({ onSubscribe }) {
const [email, setEmail] = useState("");
function handleSubmit(event) {
event.preventDefault(); // Prevent full-page browser reload
onSubscribe(email.trim());
}
return (
<form onSubmit={handleSubmit} noValidate>
<label htmlFor="newsletter-email">Work email</label>
<input
id="newsletter-email"
type="email"
value={email}
onChange={e => setEmail(e.target.value)}
required
/>
<button type="submit">Subscribe</button>
</form>
);
}
Validation strategy
Validate at the right moment so users get helpful feedback without feeling interrupted:
- On submit: Always validate the full form when the user submits so incomplete fields are caught together.
- On blur (touched): Track which fields the user has visited and display inline errors after they leave a field, rather than flashing red errors on the very first keystroke.
- Server validation: Client checks improve responsiveness, but the server remains the authority—always map backend field errors back onto the form.
Error modeling
Model validation errors as a dictionary keyed by field name (for example, { email: "Enter a valid address" }) plus an optional form-level error for server failures. Connect each message to its input with aria-invalid and aria-describedby so assistive technologies read the error immediately:
function validateProfile(values) {
const errors = {};
if (!values.name.trim()) errors.name = "Display name is required.";
if (!values.email.includes("@")) errors.email = "Enter a valid email address.";
return errors;
}
Async submit flow
When submitting to an API, track submission status explicitly (idle, submitting, succeeded, failed). Disable the submit button while a request is in flight to prevent duplicate records, clear stale errors on retry, and announce the outcome clearly:
async function handleFormSubmit(event) {
event.preventDefault();
const nextErrors = validateProfile(values);
if (Object.keys(nextErrors).length > 0) {
setErrors(nextErrors);
return;
}
setStatus("submitting");
setServerError(null);
try {
await saveProfile(values);
setStatus("succeeded");
} catch (err) {
setStatus("failed");
setServerError(err.message || "Could not save profile.");
}
}
Professional tips
Keep form code maintainable as fields and rules expand:
- Keep form state local to the form or route unless another distant view genuinely depends on unsaved drafts.
- Disable submit triggers during pending requests to prevent accidental double-submissions.
- Show actionable error text ("Password must be at least 12 characters") rather than generic failure banners.
Practice
Build a profile editor form with controlled inputs, field-keyed validation on blur and submit, accessible aria-describedby error messages, and an async submit flow with pending and failure states.