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 callsfn(formData)on submit, handlespreventDefault, and resets the form after success.useActionState(action, initialState)returns[state, formAction, isPending]for results like validation errors.useFormStatus()(fromreact-dom) givespendingto a submit button inside the form.useOptimisticshows 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, andzodResolverfor 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";34type State = { error?: string; ok?: boolean };56async 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 API10 return { ok: true };11}1213function SaveButton() {14 const { pending } = useFormStatus(); // status of the enclosing <form>15 return <button disabled={pending}>{pending ? "Saving…" : "Save"}</button>;16}1718export function ProfileForm() {19 const [state, formAction] = useActionState(saveProfile, {});2021 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.