Skip to content

Lesson 10 of 37State

Forms

Build controlled and uncontrolled forms, make errors accessible, validate async and in actions, and handle file uploads.

24 min read0/8 questions

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.

React
import { useState } from "react"; export default function App() { const [username, setUsername] = useState(""); return ( <div> <input aria-label="Username" value={username} onChange={(e) => setUsername(e.target.value.toLowerCase().replace(/\s/g, ""))} /> <p>Your profile URL: example.com/@{username || "..."}</p> </div> );}
One keystroke in a controlled input
UserInputYour codeReacttypes AonChange(e)setUsername("a")value="a"

The browser fires an input event.

1/4

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.

Quick check
<input value={name} /> with no onChange. What happens when the user types?
Need a nudge? A hint rules out a wrong answer.

Every input type

Each input type has one quirk worth memorising.

ElementValue propRead in onChange
<input type="text">valuee.target.value (a string)
<input type="number">valuee.target.value is still a string; convert with Number()
<input type="checkbox">checkede.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):

React
import { useState } from "react";import type { ChangeEvent } from "react"; type Settings = { displayName: string; plan: string; bio: string; newsletter: boolean }; export default function App() { const [form, setForm] = useState<Settings>({ displayName: "Ada", plan: "free", bio: "", newsletter: true }); function handleChange(e: ChangeEvent<HTMLInputElement | HTMLSelectElement | HTMLTextAreaElement>) { const { name, value, type } = e.target; const next = type === "checkbox" ? (e.target as HTMLInputElement).checked : value; setForm({ ...form, [name]: next }); } return ( <div style={{ display: "grid", gap: 8, maxWidth: 320 }}> <input name="displayName" aria-label="Display name" value={form.displayName} onChange={handleChange} /> <select name="plan" aria-label="Plan" value={form.plan} onChange={handleChange}> <option value="free">Free</option> <option value="pro">Pro</option> <option value="team">Team</option> </select> <textarea name="bio" aria-label="Bio" placeholder="Bio" value={form.bio} onChange={handleChange} /> <label> <input type="checkbox" name="newsletter" checked={form.newsletter} onChange={handleChange} /> Send me the newsletter </label> <pre style={{ background: "#f6f6f6", padding: 8 }}>{JSON.stringify(form, null, 2)}</pre> </div> );}
Match the pairs0/4 matched

Match each control to how you read its new value.

Choose an item, then its match on the other side.

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.
React
import { useState } from "react";import type { FormEvent } from "react"; export default function App() { const [email, setEmail] = useState(""); const [age, setAge] = useState(""); const [touched, setTouched] = useState(false); const [sent, setSent] = useState<string | null>(null); const emailError = !email.includes("@") ? "Enter a valid email address" : ""; const ageError = Number(age) < 13 ? "You must be 13 or older" : ""; const isValid = !emailError && !ageError; function handleSubmit(e: FormEvent<HTMLFormElement>) { e.preventDefault(); setTouched(true); if (!isValid) return; setSent(email); } if (sent) return <p>Thanks! We emailed {sent}.</p>; return ( <form onSubmit={handleSubmit} onBlur={() => setTouched(true)} style={{ display: "grid", gap: 6, maxWidth: 280 }}> <input aria-label="Email" placeholder="Email" value={email} onChange={(e) => setEmail(e.target.value)} /> {touched && emailError && <small style={{ color: "crimson" }}>{emailError}</small>} <input aria-label="Age" type="number" placeholder="Age" value={age} onChange={(e) => setAge(e.target.value)} /> {touched && ageError && <small style={{ color: "crimson" }}>{ageError}</small>} <button type="submit" disabled={!isValid}>Sign up</button> </form> );}

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.

  1. Every input has a real label. A <label htmlFor> pointing at the input's id, or a label wrapping the input. A placeholder is not a label: it disappears when you type and is often too faint to read.
  2. Mark invalid fields with aria-invalid="true", so assistive technology announces "invalid entry".
  3. Connect the message to the field with aria-describedby set to the error's id. When the field gets focus, the screen reader reads the label, then the error.
  4. 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.

React
import { useId, useState } from "react";import type { FormEvent } from "react"; type Values = { email: string; password: string };type Errors = Partial<Record<keyof Values, string>>; function validate(v: Values): Errors { const errors: Errors = {}; if (!v.email.includes("@")) errors.email = "Enter an email address like name@example.com"; if (v.password.length < 8) errors.password = "Use at least 8 characters"; return errors;} export default function App() { const id = useId(); const [errors, setErrors] = useState<Errors>({}); const [done, setDone] = useState(false); function handleSubmit(e: FormEvent<HTMLFormElement>) { e.preventDefault(); const form = e.currentTarget; const data = new FormData(form); const next = validate({ email: String(data.get("email") ?? ""), password: String(data.get("password") ?? "") }); setErrors(next); const firstInvalid = Object.keys(next)[0]; if (firstInvalid) { (form.elements.namedItem(firstInvalid) as HTMLInputElement).focus(); return; } setDone(true); } if (done) return <p>Signed up.</p>; return ( <form noValidate onSubmit={handleSubmit} style={{ display: "grid", gap: 4, maxWidth: 300 }}> <label htmlFor={`${id}-email`}>Email</label> <input id={`${id}-email`} name="email" type="email" aria-invalid={errors.email ? true : undefined} aria-describedby={errors.email ? `${id}-email-error` : undefined} /> {errors.email && <small id={`${id}-email-error`} style={{ color: "crimson" }}>{errors.email}</small>} <label htmlFor={`${id}-password`}>Password</label> <input id={`${id}-password`} name="password" type="password" aria-invalid={errors.password ? true : undefined} aria-describedby={errors.password ? `${id}-password-error` : undefined} /> {errors.password && <small id={`${id}-password-error`} style={{ color: "crimson" }}>{errors.password}</small>} <button type="submit" style={{ marginTop: 6 }}>Sign up</button> </form> );}

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:

  • noValidate switches off the browser's own validation bubbles, so every message comes from your code and looks the same in every browser. Keeping type="email" still gives mobile users the right keyboard.
  • form.elements.namedItem(name) finds a field by its name, 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.

Put it in order5 steps

Order what should happen when a user submits a form with two invalid fields.

  1. Tap the steps below in the right order.
Need a nudge? A hint shows where it starts.

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.

React
import { useRef, useState } from "react"; const TAKEN = ["ada", "admin", "sam"]; function isAvailable(name: string): Promise<boolean> { const delay = 300 + Math.max(0, 6 - name.length) * 200; return new Promise((resolve) => setTimeout(() => resolve(!TAKEN.includes(name.toLowerCase())), delay));} type Check = "idle" | "checking" | "available" | "taken"; export default function App() { const [name, setName] = useState(""); const [check, setCheck] = useState<Check>("idle"); const [requests, setRequests] = useState(0); const timer = useRef<ReturnType<typeof setTimeout> | undefined>(undefined); const latest = useRef(""); function handleChange(value: string) { setName(value); latest.current = value; clearTimeout(timer.current); if (value.length < 3) { setCheck("idle"); return; } setCheck("checking"); timer.current = setTimeout(async () => { setRequests((n) => n + 1); const free = await isAvailable(value); if (latest.current !== value) return; // the user typed more: this answer is stale setCheck(free ? "available" : "taken"); }, 400); } const message = { idle: "At least 3 characters", checking: "Checking...", available: "Available", taken: "Already taken" }[check]; return ( <div style={{ display: "grid", gap: 4, maxWidth: 280 }}> <label htmlFor="username">Username</label> <input id="username" value={name} onChange={(e) => handleChange(e.target.value)} aria-describedby="username-status" /> <small id="username-status" aria-live="polite" style={{ color: check === "taken" ? "crimson" : undefined }}> {message} </small> <small>Requests sent: {requests}</small> </div> );}

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.

Predict the outputJavaScript

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
Need a nudge? Hints walk you through it.

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.

React
import { useState } from "react";import type { FormEvent } from "react"; export default function App() { const [result, setResult] = useState(""); function handleSubmit(e: FormEvent<HTMLFormElement>) { e.preventDefault(); const data = new FormData(e.currentTarget); const entry = { title: data.get("title"), priority: data.get("priority"), urgent: data.get("urgent") === "on" }; setResult(JSON.stringify(entry)); } return ( <form onSubmit={handleSubmit} style={{ display: "grid", gap: 6, maxWidth: 280 }}> <input name="title" aria-label="Title" defaultValue="Fix the login bug" /> <select name="priority" aria-label="Priority" defaultValue="high"> <option value="low">Low</option> <option value="high">High</option> </select> <label> <input type="checkbox" name="urgent" /> Urgent </label> <button type="submit">Create</button> <code>{result}</code> </form> );}

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.

Quick checkPick all that apply
Which features need a controlled input? Pick all that apply.

None picked yet

Need a nudge? A hint rules out a wrong answer.

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.

React
import { useState } from "react";import type { ChangeEvent } from "react"; const MAX_BYTES = 2 * 1024 * 1024; export default function App() { const [preview, setPreview] = useState<string | null>(null); const [error, setError] = useState(""); const [inputKey, setInputKey] = useState(0); function release() { if (preview) URL.revokeObjectURL(preview); setPreview(null); } function handleFile(e: ChangeEvent<HTMLInputElement>) { release(); setError(""); const file = e.target.files?.[0]; if (!file) return; if (!file.type.startsWith("image/")) return setError("Choose an image file (PNG, JPEG, WebP)."); if (file.size > MAX_BYTES) return setError(`That file is ${(file.size / 1024 / 1024).toFixed(1)} MB. The limit is 2 MB.`); setPreview(URL.createObjectURL(file)); } function remove() { release(); setInputKey((k) => k + 1); // a new key mounts a fresh, empty file input } return ( <div style={{ display: "grid", gap: 6, maxWidth: 320 }}> <label htmlFor="avatar">Profile picture</label> <input key={inputKey} id="avatar" type="file" name="avatar" accept="image/*" onChange={handleFile} aria-describedby="avatar-help" /> <small id="avatar-help" style={{ color: error ? "crimson" : undefined }}>{error || "PNG, JPEG or WebP, up to 2 MB."}</small> {preview && ( <> <img src={preview} alt="Preview of your new profile picture" width={96} height={96} style={{ objectFit: "cover" }} /> <button type="button" onClick={remove}>Remove</button> </> )} </div> );}

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 setting inputRef.current.value = "". Clearing also matters for a quieter reason: choosing the same file twice fires no change event unless the input was cleared.
  • accept is a hint, not a check. It filters the picker, but users can still choose any file. Check type and size in 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 FormData includes the File under its field name. With fetch(url, { method: "POST", body: formData }), do not set the Content-Type header yourself: the browser adds multipart/form-data with the boundary it needs, and a hand-written header breaks the upload.
  • Several files. Add multiple and loop over Array.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.

Quick check
A user picks photo.png, you show a preview, they click Remove, then pick photo.png again. Nothing happens. Why?
Need a nudge? A hint rules out a wrong answer.

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.

React
import { useActionState } from "react"; type Result = { ok: boolean; message: string }; async function subscribe(previous: Result, formData: FormData): Promise<Result> { await new Promise((r) => setTimeout(r, 800)); // pretend to call a server const name = String(formData.get("name") ?? "").trim(); if (!name) return { ok: false, message: "Please enter your name." }; return { ok: true, message: `Welcome aboard, ${name}!` };} export default function App() { const [result, formAction, isPending] = useActionState(subscribe, { ok: false, message: "" }); return ( <form action={formAction} style={{ display: "flex", gap: 6, flexWrap: "wrap" }}> <input name="name" aria-label="Name" placeholder="Your name" /> <button type="submit" disabled={isPending}>{isPending ? "Subscribing..." : "Subscribe"}</button> {result.message && <p style={{ width: "100%", color: result.ok ? "green" : "crimson" }}>{result.message}</p>} </form> );}

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.

Put it in order5 steps

Order what happens when a user submits a form wired to useActionState.

  1. Tap the steps below in the right order.
Need a nudge? A hint shows where it starts.

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.)

React
import { useActionState, useId } from "react"; type Fields = { email: string; password: string };type State = { errors: Partial<Record<keyof Fields, string>>; values: Fields; message: string }; const EXISTING = ["ada@example.com"];const wait = (ms: number) => new Promise((r) => setTimeout(r, ms)); async function register(previous: State, data: FormData): Promise<State> { const values = { email: String(data.get("email") ?? "").trim(), password: String(data.get("password") ?? "") }; const errors: State["errors"] = {}; if (!values.email.includes("@")) errors.email = "Enter an email address like name@example.com"; if (values.password.length < 8) errors.password = "Use at least 8 characters"; if (!errors.email) { await wait(500); // pretend to ask the server if (EXISTING.includes(values.email.toLowerCase())) errors.email = "An account with this email already exists"; } if (Object.keys(errors).length > 0) return { errors, values: { ...values, password: "" }, message: "" }; return { errors: {}, values: { email: "", password: "" }, message: `Account created for ${values.email}.` };} const initial: State = { errors: {}, values: { email: "", password: "" }, message: "" }; export default function App() { const [state, formAction, isPending] = useActionState(register, initial); const id = useId(); const { errors } = state; return ( <form action={formAction} noValidate style={{ display: "grid", gap: 4, maxWidth: 300 }}> <label htmlFor={`${id}-email`}>Email</label> <input id={`${id}-email`} name="email" type="email" defaultValue={state.values.email} aria-invalid={errors.email ? true : undefined} aria-describedby={errors.email ? `${id}-email-err` : undefined} /> {errors.email && <small id={`${id}-email-err`} style={{ color: "crimson" }}>{errors.email}</small>} <label htmlFor={`${id}-pw`}>Password</label> <input id={`${id}-pw`} name="password" type="password" aria-invalid={errors.password ? true : undefined} aria-describedby={errors.password ? `${id}-pw-err` : undefined} /> {errors.password && <small id={`${id}-pw-err`} style={{ color: "crimson" }}>{errors.password}</small>} <button type="submit" disabled={isPending} style={{ marginTop: 6 }}>{isPending ? "Creating account..." : "Create account"}</button> {state.message && <p role="status">{state.message}</p>} </form> );}

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 like z.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, required and client checks can all be bypassed. The action validates everything, every time.
features/signup/schema.ts
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.

Quick check
A form uses <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?
Need a nudge? A hint rules out a wrong answer.
ChallengeMedium

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 label I 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 example Welcome, ada@example.com!).
React
import { useState } from "react";import type { FormEvent } from "react"; export default function App() { // Add state for email, password, terms, and whether the form was submitted. return ( <form> <input type="text" name="email" aria-label="Email" /> <input type="password" name="password" aria-label="Password" /> <label> <input type="checkbox" name="terms" /> I accept the terms </label> <button type="submit">Sign up</button> </form> );}
Key terms
controlled input
An input whose value comes from state and whose onChange writes 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-dom hook that lets a component inside a form read its pending status.
aria-describedby
Points an input at the id of 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 from URL.createObjectURL(file) for previewing a local file. Release it with revokeObjectURL.