Lesson 10 of 37State
Forms
Build controlled and uncontrolled forms, make errors accessible, validate async and in actions, and handle file uploads.
Sign-up, checkout, search, settings, comments: forms are where users give your app data, and where most of the fiddly UI bugs live. A take-home assignment almost always includes one. This lesson covers the controlled pattern you will use most, every input type's quirks, validation, the simpler uncontrolled approach, and the React 19 form actions that frameworks like Next.js build on.
Controlled inputs
A controlled input gets its value from state (value={x}) and reports every change (onChange), which you write back into state. React state is the single source of truth, and the input just displays it.
The browser fires an input event.
Type some capital letters and spaces. Because your code decides what goes into state, you can transform input as it is typed. And because the value lives in state, other parts of the UI (the URL preview) update for free.
If you set value without onChange, React makes the input read-only and warns you. Every keystroke is rejected because state never changes.
<input value={name} /> with no onChange. What happens when the user types?Every input type
Each input type has one quirk worth memorising.
| Element | Value prop | Read in onChange |
|---|---|---|
<input type="text"> | value | e.target.value (a string) |
<input type="number"> | value | e.target.value is still a string; convert with Number() |
<input type="checkbox"> | checked | e.target.checked (a boolean) |
<select> | value on the <select> | e.target.value |
<textarea> | value (not children) | e.target.value |
With many fields, keep one state object and use each input's name attribute to update the right key with a computed property name ([name]: value):
Match each control to how you read its new value.
Submitting and validating
Put the submit logic on the form's onSubmit (so Enter works), call e.preventDefault(), and derive validation from state during render. Two details make validation feel friendly:
- Show an error only after the user has interacted with the field (or tried to submit), not while the form is still empty.
- Disable the submit button while the form is invalid, and check again in the submit handler.
Accessible errors and focus
The form above works for a sighted mouse user. For someone using a screen reader, the error messages are just text floating somewhere on the page, with nothing linking them to the fields. Accessible forms are tested in interviews, flagged in code review, and in many countries required by law. Four habits cover most of it.
- Every input has a real label. A
<label htmlFor>pointing at the input'sid, or a label wrapping the input. A placeholder is not a label: it disappears when you type and is often too faint to read. - Mark invalid fields with
aria-invalid="true", so assistive technology announces "invalid entry". - Connect the message to the field with
aria-describedbyset to the error'sid. When the field gets focus, the screen reader reads the label, then the error. - Move focus to the first invalid field on submit. Otherwise a keyboard or screen reader user presses Enter and nothing seems to happen.
Ids must be unique on the page, and a component can render many times. useId() gives each instance its own stable id, which also matches between server and client rendering.
Submit it empty: focus jumps to Email. Fix the email and submit again: focus jumps to Password. A few decisions in that code are worth defending in review:
noValidateswitches off the browser's own validation bubbles, so every message comes from your code and looks the same in every browser. Keepingtype="email"still gives mobile users the right keyboard.form.elements.namedItem(name)finds a field by itsname, so focusing needs no extra refs.- The button is not disabled. A disabled button cannot receive focus, gives no reason why it is disabled, and is skipped by many screen readers. The earlier example disabled it to show the idea, but many design systems now keep submit enabled and show the errors when it is pressed. If you do disable it, say what is missing next to it.
- Error text says how to fix the problem ("Use at least 8 characters"), not just that there is one ("Invalid password").
On long forms, add an error summary at the top with links to each field, and move focus to the summary. Do not rely on colour alone: the red is decoration, the text carries the meaning. The accessible components lesson goes further with live regions and focus management in dialogs.
Order what should happen when a user submits a form with two invalid fields.
- Tap the steps below in the right order.
Debounced async validation
Some checks need the server: is this username taken, is this coupon real, is this VAT number valid. Calling the API on every keystroke wastes requests and can show results in the wrong order. Two techniques fix it.
Debounce: wait until the user has stopped typing for a moment (300 to 500 ms is typical) before sending anything. Ignore stale responses: remember the latest value, and when a response arrives for an older one, throw it away. Responses do not always come back in the order you sent them.
This version debounces inside the change handler, with no effect needed. useRef (which the refs lesson covers) holds the timer and the latest value between renders without causing re-renders. Type ad, then keep going to ada, then adams. The fake server answers more slowly for short names.
Type quickly and the request count barely moves. The aria-live="polite" region makes a screen reader announce "Available" or "Already taken" when it changes, without stealing focus.
In production you would also cancel the outdated request itself with an AbortController, so the network is not busy with answers you will ignore. And the async check is still only a hint: two people can claim the same name in the same second. The server must enforce uniqueness when the form is submitted, with a database constraint, and return a field error if it loses the race. The custom hooks lesson packages the timer part as a reusable useDebounce.
Using the component above, a user types adams one letter every 100 ms and then stops. How many requests does it send?
// keystrokes at 0, 100, 200, 300, 400 ms // values: "a", "ad", "ada", "adam", "adams" // debounce: 400 ms, minimum length: 3
Uncontrolled inputs and FormData
Not every form needs state for every field. If you only need the values on submit, let the browser keep them (an uncontrolled input) and read them all at once with the browser's FormData API. Use defaultValue (or defaultChecked) to set a starting value without controlling it.
Every field needs a name, because that is the key FormData uses. Choose controlled when the UI reacts to each keystroke (live validation, previews, dependent fields); choose uncontrolled when you just need the values at the end.
None picked yet
File inputs and previews
<input type="file"> is the one input React cannot control. For security, a page cannot set which file is selected, so the only value you may write is an empty string. You read the choice from e.target.files, a list of File objects, and keep whatever you need in state.
The most common job is showing a preview before uploading. URL.createObjectURL(file) returns a temporary blob: URL that an <img> can display straight away, with no upload. Each URL holds the file in memory until you release it with URL.revokeObjectURL, so revoke the old one whenever you replace or remove it.
Things that trip people up:
- Clearing the input. Since you cannot control it, reset it by giving it a new
key(as above) or by settinginputRef.current.value = "". Clearing also matters for a quieter reason: choosing the same file twice fires nochangeevent unless the input was cleared. acceptis a hint, not a check. It filters the picker, but users can still choose any file. Checktypeandsizein your code for a friendly message, and check again on the server, where the file's contents, not its name or claimed type, are what count.- Sending it. A form's
FormDataincludes theFileunder its field name. Withfetch(url, { method: "POST", body: formData }), do not set theContent-Typeheader yourself: the browser addsmultipart/form-datawith the boundary it needs, and a hand-written header breaks the upload. - Several files. Add
multipleand loop overArray.from(e.target.files). - Cleanup on unmount. If the component can disappear while a preview exists, revoke the URL in an effect's cleanup. The effects lesson shows how.
Large uploads such as videos usually skip your own server entirely: the backend hands the browser a short-lived signed URL, and the file goes straight to object storage.
photo.png, you show a preview, they click Remove, then pick photo.png again. Nothing happens. Why?React 19: form actions
React 19 added actions: you can pass a function (sync or async) to a form's action prop. React calls it with the FormData when the form submits, with no preventDefault needed, and it resets uncontrolled fields after a successful submit.
The hook useActionState(action, initialState) wraps an action and gives you three things: the latest result returned by the action, a wrapped action to pass to the form, and an isPending flag that is true while an async action runs. Try submitting an empty name, then a real one.
A companion hook, useFormStatus from react-dom, lets a component inside a form read whether that form is submitting, so a reusable submit button can show its own spinner without props:
import { useFormStatus } from "react-dom";
function SubmitButton() {
const { pending } = useFormStatus();
return <button type="submit" disabled={pending}>{pending ? "Saving..." : "Save"}</button>;
}These shine with a server: in Next.js, the action can be a Server Action that runs on the server and writes to your database, with no API route in between. The Next.js course goes deep on that. In a client-only app, controlled forms with onSubmit are still the everyday tool.
Order what happens when a user submits a form wired to useActionState.
- Tap the steps below in the right order.
useActionState with validation errors
The subscribe example returned one message. Real forms need an error per field, and they need the user's input to survive a failed submit. Two facts shape the pattern.
First, the action is where validation really happens. In Next.js it runs on the server, and even in a client-only app it is the last stop before your API. So the action returns a structured result: the errors for each field, plus the values that were submitted. Second, when a form action finishes, React resets the form's uncontrolled fields, even when you returned errors. Feed the submitted values back as defaultValue and the reset restores what the user typed. (The actions lesson explains the reset in more detail.)
Try ada@example.com with a long password to see a server-side error, then an email with no @. The email survives each failed submit because it comes back in state.values. The password deliberately does not: never send a password back to the browser in a response, so the user types it again.
How this scales on a real team:
- One schema for both sides. Define the rules once with a schema library and run them in the action, and optionally on the client for instant feedback. With Zod that looks like the block below. Check the Zod docs for the exact error helpers in your version; Zod 4 moved them from methods like
error.flatten()to functions likez.flattenError(error). - Field errors and form errors are different. "Email already exists" belongs to a field. "Payment provider is down" belongs to the whole form, so return it separately and show it near the button.
- Never trust the client. Disabled buttons,
requiredand client checks can all be bypassed. The action validates everything, every time.
import { z } from "zod";
export const SignupSchema = z.object({
email: z.email("Enter an email address like name@example.com"),
password: z.string().min(8, "Use at least 8 characters"),
});
// inside the action
const result = SignupSchema.safeParse(Object.fromEntries(formData));
if (!result.success) {
const { fieldErrors } = z.flattenError(result.error); // { email?: string[]; password?: string[] }
return {
errors: { email: fieldErrors.email?.[0], password: fieldErrors.password?.[0] },
values: { email: String(formData.get("email") ?? ""), password: "" },
};
}
// result.data is typed { email: string; password: string }The forms at scale lesson builds on this with React Hook Form for large client-side forms.
<form action={formAction}> with uncontrolled inputs. The action returns an error for a bad email, and the user's text disappears. What is the fix?Sign-up form with validation
Build a controlled sign-up form.
<input type="text" name="email" aria-label="Email"><input type="password" name="password" aria-label="Password"><input type="checkbox" name="terms">with a labelI accept the terms- A submit button
Sign up, disabled until the form is valid: the email contains@, the password has at least 8 characters, and the box is checked. - While the password is non-empty but shorter than 8 characters, show
<p className="error">Password must be at least 8 characters</p>. Do not show it when the password is empty. - On submit, prevent the page reload and replace the form with
<p>Welcome, EMAIL!</p>(for exampleWelcome, ada@example.com!).
- controlled input
- An input whose
valuecomes from state and whoseonChangewrites back to state. - uncontrolled input
- An input that keeps its own value in the DOM. Start it with
defaultValue; read it on submit. - FormData
- A browser API that collects a form's named fields:
new FormData(form).get("email"). - form action
- React 19: a function passed to
<form action={fn}>, called with the form's FormData on submit. - useActionState
- React 19 hook returning
[result, formAction, isPending]for a form action. - useFormStatus
- A
react-domhook that lets a component inside a form read itspendingstatus. - aria-describedby
- Points an input at the
idof text that describes it, such as its error, so screen readers read both. - useId
- A hook that returns a unique, stable id per component instance, matching on server and client.
- debounce
- Waiting until input has stopped changing for a set time before acting on it.
- object URL
- A temporary
blob:URL fromURL.createObjectURL(file)for previewing a local file. Release it withrevokeObjectURL.