ReactMedium

How to handle forms in React?

Choose a strategy by complexity: React 19 form Actions with FormData for simple submits, controlled inputs with useState when the UI must react to every keystroke, and a form library such as React Hook Form with a schema validator (Zod) for large forms. Show pending and error states with useActionState and useFormStatus.

1. React 19 Actions

  • <form action={fn}>: React calls fn(formData) on submit, handles preventDefault, and resets the form after success.
  • useActionState(action, initialState) returns [state, formAction, isPending] for results like validation errors.
  • useFormStatus() (from react-dom) gives pending to a submit button inside the form.
  • useOptimistic shows the expected result immediately.
  • Works with Server Functions in frameworks like Next.js.

2. Controlled inputs

value + onChange per field. Best for live validation, dependent fields and formatting.

3. Libraries

  • React Hook Form: uncontrolled, minimal re-renders, register, handleSubmit, and zodResolver for schema validation.
  • TanStack Form: type-safe and framework-agnostic.
  • Formik: older and still used, but much less active.

Validation

  • HTML attributes (required, type="email", pattern, min) for free browser validation.
  • A schema (Zod, Valibot) shared between client and server.
  • Always validate again on the server.

Accessibility

Label every input (<label htmlFor>), connect errors with aria-describedby, mark invalid fields with aria-invalid, and move focus to the first error on submit.

Code example

tsx
1import { useActionState } from "react";
2import { useFormStatus } from "react-dom";
3
4type State = { error?: string; ok?: boolean };
5
6async function saveProfile(_prev: State, formData: FormData): Promise<State> {
7 const name = String(formData.get("name") ?? "").trim();
8 if (name.length < 2) return { error: "Name must be at least 2 characters" };
9 await new Promise((r) => setTimeout(r, 500)); // pretend to call an API
10 return { ok: true };
11}
12
13function SaveButton() {
14 const { pending } = useFormStatus(); // status of the enclosing <form>
15 return <button disabled={pending}>{pending ? "Saving…" : "Save"}</button>;
16}
17
18export function ProfileForm() {
19 const [state, formAction] = useActionState(saveProfile, {});
20
21 return (
22 <form action={formAction}>
23 <label htmlFor="name">Name</label>
24 <input id="name" name="name" aria-invalid={!!state.error} aria-describedby="name-error" />
25 {state.error && <p id="name-error" role="alert">{state.error}</p>}
26 {state.ok && <p role="status">Saved!</p>}
27 <SaveButton />
28 </form>
29 );
30}

Practice this question

Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the React set.

Open in study app