Lesson 8 of 11 · 14 min · Building apps
Forms in React: controlled inputs, validation and actions
What you will learn
- Build controlled inputs with
valueandonChange - Handle submit, validation and error messages
- Use uncontrolled inputs with
FormDataand refs - Use React 19 form actions:
action,useActionState,useFormStatus - Choose React Hook Form with Zod for larger forms; keep forms accessible
In simple words
A form is where a user gives your app information. The browser already knows how to collect the fields; React's job is to keep track of what has been typed, check it, show friendly messages and send it. There are two styles: let React hold every keystroke (a controlled form), or let the browser hold the values and read them when the form is sent (an uncontrolled form). Both are fine; the right choice depends on the form.
Words to know
- Controlled input: an input whose value is stored in React state.
- Uncontrolled input: an input that keeps its own value in the DOM, read when needed.
- Validation: checking the entered data against rules.
- Form action: a function React calls when a form is submitted.
Controlled inputs
import { useState } from "react";
function SignUpForm() {
const [email, setEmail] = useState("");
const [role, setRole] = useState("data-analyst");
const [agree, setAgree] = useState(false);
function handleSubmit(event: React.FormEvent<HTMLFormElement>) {
event.preventDefault(); // stop the browser's page-reloading submit
console.log({ email, role, agree });
}
return (
<form onSubmit={handleSubmit} noValidate>
<label htmlFor="email">Email</label>
<input id="email" type="email" value={email} onChange={(e) => setEmail(e.target.value)} autoComplete="email" required />
<label htmlFor="role">Target job</label>
<select id="role" value={role} onChange={(e) => setRole(e.target.value)}>
<option value="data-analyst">Data Analyst</option>
<option value="java-developer">Java Developer</option>
</select>
<label>
<input type="checkbox" checked={agree} onChange={(e) => setAgree(e.target.checked)} />
I agree to the terms
</label>
<button type="submit" disabled={!agree}>Create account</button>
</form>
);
}
- The state is the source of truth; the input shows
valueand reports changes throughonChange. Checkboxes usechecked; radio buttonschecked={value === "x"}; selects and textareas usevalue. - Always connect
<label htmlFor>toid, set the righttype,autoCompleteandinputMode(the HTML forms lesson). - A
valuewithoutonChangemakes the field read-only (React warns). Never setvaluetoundefinedornulland later a string (it switches between uncontrolled and controlled); use"". - For many fields, one state object and one handler using the input's
name:
const [form, setForm] = useState({ name: "", email: "" });
const handleChange = (e: React.ChangeEvent<HTMLInputElement>) =>
setForm((f) => ({ ...f, [e.target.name]: e.target.value }));
<input name="name" value={form.name} onChange={handleChange} />
<input name="email" value={form.email} onChange={handleChange} />
Controlled inputs let you validate as the user types, format input (uppercase a PAN number), enable or disable buttons and keep other UI in sync. The cost is a re-render on every keystroke, which is fine for ordinary forms.
Uncontrolled inputs and FormData
If you only need the values at submit time, let the DOM hold them:
function SearchForm({ onSearch }: { onSearch: (q: string) => void }) {
function handleSubmit(event: React.FormEvent<HTMLFormElement>) {
event.preventDefault();
const data = new FormData(event.currentTarget);
onSearch(String(data.get("q") ?? ""));
}
return (
<form onSubmit={handleSubmit} role="search">
<label htmlFor="q">Search</label>
<input id="q" name="q" type="search" defaultValue="" />
<button type="submit">Go</button>
</form>
);
}
defaultValue sets the initial value; name is required for FormData. Use a ref (useRef) to read or focus a single input. Uncontrolled forms are simpler and faster for forms without live behaviour, and are what React Hook Form uses internally.
Validation
Validate in three layers: HTML attributes (required, type="email", minLength, pattern) for quick feedback; JavaScript for rules that need logic and nicer messages; and the server, always (client checks can be bypassed).
type Errors = Partial<Record<"email" | "password", string>>;
function validate(values: { email: string; password: string }): Errors {
const errors: Errors = {};
if (!/^\S+@\S+\.\S+$/.test(values.email)) errors.email = "Enter a valid email address.";
if (values.password.length < 8) errors.password = "Use at least 8 characters.";
return errors;
}
function LoginForm() {
const [values, setValues] = useState({ email: "", password: "" });
const [errors, setErrors] = useState<Errors>({});
const [touched, setTouched] = useState<Record<string, boolean>>({});
const [submitting, setSubmitting] = useState(false);
const [serverError, setServerError] = useState("");
async function handleSubmit(event: React.FormEvent) {
event.preventDefault();
const found = validate(values);
setErrors(found);
if (Object.keys(found).length > 0) return;
setSubmitting(true);
setServerError("");
try {
await login(values);
} catch {
setServerError("Email or password is incorrect.");
} finally {
setSubmitting(false);
}
}
return (
<form onSubmit={handleSubmit} noValidate>
<div>
<label htmlFor="email">Email</label>
<input
id="email" type="email" value={values.email} autoComplete="email"
aria-invalid={Boolean(errors.email)} aria-describedby={errors.email ? "email-error" : undefined}
onChange={(e) => setValues({ ...values, email: e.target.value })}
onBlur={() => setTouched({ ...touched, email: true })}
/>
{errors.email && <p id="email-error" role="alert">{errors.email}</p>}
</div>
{/* password field similar */}
{serverError && <p role="alert">{serverError}</p>}
<button type="submit" disabled={submitting}>{submitting ? "Signing in..." : "Sign in"}</button>
</form>
);
}
UX rules:
- Do not show errors before the user has had a chance: validate on blur or on submit (the
touchedpattern), then on change after the first error. - Put the message next to the field, connect it with
aria-describedby, setaria-invalid, and userole="alert"(or move focus to the first error or an error summary) so screen readers announce it. - Say how to fix it ("Use at least 8 characters"), not just "Invalid".
- Disable the submit button while sending to prevent double submissions, and show progress.
- Keep the user's input after an error; never clear the form.
- Show server-side errors next to the matching fields (map the API's field errors), plus a general message.
- Do not rely on colour alone.
React 19 form actions
React 19 lets you pass a function to a form's action. React calls it on submit with the FormData, resets uncontrolled fields afterwards, and tracks the pending state:
import { useActionState } from "react";
type FormState = { error?: string; success?: boolean };
async function subscribeAction(_prev: FormState, formData: FormData): Promise<FormState> {
const email = String(formData.get("email") ?? "");
if (!/^\S+@\S+\.\S+$/.test(email)) return { error: "Enter a valid email address." };
const response = await fetch("/api/subscribe", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ email }),
});
return response.ok ? { success: true } : { error: "Could not subscribe. Try again." };
}
function Subscribe() {
const [state, formAction, isPending] = useActionState(subscribeAction, {});
return (
<form action={formAction}>
<label htmlFor="email">Email</label>
<input id="email" name="email" type="email" required />
<button type="submit" disabled={isPending}>{isPending ? "Subscribing..." : "Subscribe"}</button>
{state.error && <p role="alert">{state.error}</p>}
{state.success && <p role="status">Thank you for subscribing.</p>}
</form>
);
}
useActionState(action, initialState)returns[state, formAction, isPending]: the latest result of your action, the function to pass toaction, and whether it is running.useFormStatus()(fromreact-dom) lets a child of the form (a reusableSubmitButton) readpendingwithout props.useOptimisticshows an expected result immediately while the action runs.- In frameworks with server functions ("Server Actions"), the action can run on the server; the same hooks work for client-side actions.
Actions give you pending state, error handling and form reset with less code, while keeping the form usable without extra state; they suit simple and moderate forms.
React Hook Form and Zod
For larger forms (many fields, complex rules, dynamic arrays, performance), use React Hook Form (RHF): it uses uncontrolled inputs, so typing does not re-render the whole form, and handles touched state, errors and submission. Pair it with Zod to define the rules once, in a schema, and derive the TypeScript type:
import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { z } from "zod";
const schema = z.object({
name: z.string().min(2, "Enter your full name"),
email: z.string().email("Enter a valid email"),
phone: z.string().regex(/^[6-9]\d{9}$/, "Enter a 10-digit Indian mobile number"),
});
type FormValues = z.infer<typeof schema>;
function Profile() {
const { register, handleSubmit, formState: { errors, isSubmitting } } = useForm<FormValues>({
resolver: zodResolver(schema),
});
const onSubmit = async (values: FormValues) => { await saveProfile(values); };
return (
<form onSubmit={handleSubmit(onSubmit)} noValidate>
<label htmlFor="name">Full name</label>
<input id="name" {...register("name")} aria-invalid={!!errors.name} />
{errors.name && <p role="alert">{errors.name.message}</p>}
{/* email and phone similar */}
<button type="submit" disabled={isSubmitting}>Save</button>
</form>
);
}
The same Zod schema can validate the data again on the server (in a Node.js API), keeping client and server rules aligned. Alternatives include TanStack Form and Formik (older).
Special inputs
- File upload:
<input type="file" onChange={(e) => setFile(e.target.files?.[0] ?? null)} />, send withFormData; check type and size on the client and the server; show previews withURL.createObjectURL(and revoke). - Debounced search fields: keep the typed value in state and debounce the request.
- Dependent fields (state then city): derive options from the selected value; reset dependent fields when the parent changes.
- Dynamic lists of fields (add another skill): arrays in state with stable ids as keys, or RHF's
useFieldArray. - Date and numeric fields: prefer
type="date"and string state, and parse at submit; avoidtype="number"for IDs and phone numbers. - Prevent accidental data loss: warn when leaving with unsaved changes.
Common mistakes
- Forgetting
event.preventDefault(), so the page reloads. - A controlled input without
onChange, or switching betweenundefinedand a string. - Using one state update per keystroke for huge forms without noticing the cost.
- Showing errors on first render or before interaction.
- No labels, or errors not linked to fields.
- Client-only validation.
- Clearing the form on error.
- No pending state, allowing double submits.
Try it yourself
- Build a sign-up form with controlled inputs, a checkbox and a select, and show its state under the form.
- Add validation on blur and submit, accessible error messages and a server error.
- Rebuild a search form as an uncontrolled form with
FormData. - Write the same subscribe form using
useActionStateand aSubmitButtonwithuseFormStatus. - Rebuild the profile form with React Hook Form and a Zod schema, and reuse the schema in a test.
Check yourself
What is a controlled input?
An input whose value is held in React state and updated through onChange, so the state is the single source of truth.
Why call event.preventDefault() in a submit handler?
To stop the browser's default form submission, which would reload the page and discard React state.
When should validation errors appear?
After the user has interacted, typically on blur and on submit, not on the first render; they should be near the field and announced to assistive technology.
What does useActionState return?
The current state returned by the action, a function to pass to the form's action, and a pending flag.
Interview questions
Controlled versus uncontrolled components: when do you use each?
Controlled when you need live validation, formatting or dependent UI because React state drives the value; uncontrolled for simple forms where you only need the values on submit, which is simpler and avoids re-rendering on each keystroke.
How do you validate forms in React?
Use HTML constraints plus JavaScript rules, or a schema library like Zod with React Hook Form; show accessible, specific messages on blur or submit; and always validate again on the server.
How would you handle server validation errors?
Return field-level errors (for example as problem details), map them to the matching fields in the form state, show a general message for others, and keep the user's input.
Summary
- Controlled inputs keep value in state; uncontrolled inputs use
FormDataand refs; always prevent the default submit when handling it yourself. - Validate on blur and submit, link accessible messages with
aria-describedby, disable the button while pending, and keep user input. - React 19
action,useActionStateanduseFormStatussimplify pending and result handling. - For big forms use React Hook Form with a Zod schema, and validate on the server too.
Going deeper
- React: Reacting to input with state: designing form states.
- React:
<input>component: controlled and uncontrolled inputs. - React: useActionState: form actions and state.
- React Hook Form documentation: installation, validation and resolvers.
See how much of this you can explain
A free mock interview asks you new questions on React: components, state, routing and testing for Frontend Developer and scores every answer, with what to fix.