Advanced React 01 · Forms
Forms and React 19 Actions
Which tool for which form, controlled vs. uncontrolled, checking with HTML attributes, Actions with useActionState and useFormStatus, a form in practice and useOptimistic.
Loading lesson…
Advanced React 01 · Forms
Which tool for which form, controlled vs. uncontrolled, checking with HTML attributes, Actions with useActionState and useFormStatus, a form in practice and useOptimistic.
Loading lesson…
You know a controlled field from lesson React basics 03: value from state and an onChange that writes into state. Let's use it to write a real sign-up form – a name, an e-mail and a consent – that is sent to a server:
function Signup() {const [name, setName] = useState('')const [email, setEmail] = useState('')const [agree, setAgree] = useState(false)const [isPending, setIsPending] = useState(false) // is it sending?const [error, setError] = useState<string | null>(null) // an error from the server// React.FormEvent<HTMLFormElement> = the type of the event "the form is being submitted"async function handleSubmit(e: React.FormEvent<HTMLFormElement>) {e.preventDefault() // otherwise the browser would reload the pageif (isPending) return // protection against a double clickif (name.length < 2) return setError('The name is too short') // store the error and stop (return)if (!email.includes('@')) return setError('Invalid e-mail')setIsPending(true)setError(null)try {await registerUser({ name, email }) // registerUser = a function of the course's fake APIsetName(''); setEmail(''); setAgree(false) // clear the form} catch (err) {setError((err as Error).message)} finally {setIsPending(false)}}// …and JSX with three fields, each with value and onChange}
It works. But look how much of it has nothing to do with signing up:
onChange. A form with ten fields = ten pieces of state.React and its ecosystem have a tool for each of those things. This lesson covers the ones built into React and the browser: native forms, Actions and optimistic UI (a change shows on the page before the server confirms it). The next two lessons add libraries used almost always in practice: Zod for the rules and React Hook Form for big forms.
At the town hall you can fill in a form in two ways. Either you take it to a desk, fill it in in peace and hand it over at the counter – the clerk checks it only there. Or you sit with a clerk who looks over your shoulder and immediately says at every field: "the postcode is missing here".
The table is a map of the whole topic: a typical form on the left, the tool in the middle, where to find it on the right:
| Form | Tool | Where |
|---|---|---|
| a search field that filters while you type | a controlled field (useState) | section 1 |
| contact, newsletter, a comment – the values are enough on submit | uncontrolled fields + an action + useActionState | sections 1 and 2 |
| a like, adding to a cart – it should show at once | useOptimistic | section 3 |
| sign-in, sign-up – rules for the fields and the same check on the server | an action + a Zod schema | lesson Advanced React 02 |
| a big form: many fields, repeating rows, errors after leaving a field | React Hook Form + Zod | lesson Advanced React 03 |
When: when you need to react to the value while typing. Say a field for a discount code in the format ABC-123: the letters should turn into capitals by themselves and it should show at once whether the code is valid.
function CouponField() {const [code, setCode] = useState('')const valid = /^[A-Z]{3}-\d{3}$/.test(code) // calculated during render (React basics 03)return (<><inputvalue={code}// toUpperCase = into capitals, slice(0, 7) = at most 7 charactersonChange={(e) => setCode(e.target.value.toUpperCase().slice(0, 7))}/><span>{valid ? '✓ Valid code' : 'Format: ABC-123'}</span></>)}
onChange gets "a", turns it into "A" and stores it in state.value="A". There's a capital A in the field – even though you typed a small one.valid is calculated and the message below the field updates.When: when you need the values only on submit – and that's most forms. A form with a city and a T-shirt size:
function ShippingForm() {function handleSubmit(e: React.FormEvent<HTMLFormElement>) {e.preventDefault()const data = new FormData(e.currentTarget) // currentTarget = the form the handler is attached toconsole.log(data.get('city'), data.get('size')) // the values by the name attribute}return (<form onSubmit={handleSubmit}><input name="city" defaultValue="London" /><select name="size" defaultValue="M">…</select><button>Submit</button></form>)}
useState. The browser holds the value, just like in plain HTML.defaultValue is just the initial value. React sets it once and then leaves the field alone.FormData by the name attribute.| Controlled | Uncontrolled | |
|---|---|---|
| where the value is | in React’s state (value + onChange) | in the browser (defaultValue, read through FormData) |
| render while typing | on every character | none |
| suits | live checking, formatting, fields depending on another field | most forms: the values are enough on submit |
The table reads by rows; the middle column is controlled, the right one uncontrolled.
What you see: On the left the discount code field (controlled). On the right the form with a city and a size (uncontrolled).
Try it:
abc-12 in small letters into the left field. The letters turn into capitals at once and the field is red. Add 3 – the message changes to "✓ Valid code".FormData.The takeaway: You can steer a controlled field on every letter. Uncontrolled is simpler and enough where you need the value only on submit.
Loading the interactive part…
Before you start writing your own checks, use what the browser can do. A few attributes and a form with a wrong value isn't sent at all – the browser shows a bubble at the field that's wrong:
<form onSubmit={handleSubmit}><label><input name="email" type="email" required autoComplete="email" /></label><label>Password<input name="password" type="password" required minLength={8} autoComplete="new-password" /></label><label>Postcode<input name="zip" pattern="[A-Za-z0-9 ]{5,8}" /> {/* 5 to 8 letters, digits or spaces */}</label><button>Submit</button></form>
What each attribute does. The attribute on the left, what it checks or improves in the middle, a note on the right:
| Attribute | What it does | Note |
|---|---|---|
required | the field must not stay empty | for a checkbox: it must be ticked |
type="email" | the value must look like an e-mail; on a phone, a keyboard with @ | type="number", "tel", "url" similarly |
minLength, maxLength | the fewest / most characters | for numbers min and max |
pattern | the value must match a regular expression | the whole value – ^ and $ aren’t written |
autoComplete | the browser offers saved details and passwords | email, name, new-password, current-password… |
inputMode | which keyboard shows on a phone | numeric = digits only |
What for: sending to a server has the same worries in every form – waiting, errors, double clicks, clearing. In the introduction you wrote them by hand. In React 19 you can pass a function to <form action>: React calls it with FormData, keeps track of whether it's still running, and clears the form when it's done. Plus two helpers.
import { useActionState } from 'react'interface FormState {errors?: { name?: string; email?: string } // an error at a particular fieldmessage?: string // a success messagevalues?: { name: string; email: string } // what the user filled in – we put it back into the fields after an error}// An action: it gets the previous result and the filled-in form and returns a new result. It may be async.async function signup(prev: FormState, formData: FormData): Promise<FormState> {const name = String(formData.get('name') ?? '').trim() // trim = without spaces at the start and endconst email = String(formData.get('email') ?? '').trim()const values = { name, email }if (name.length < 2) return { errors: { name: 'The name must have at least 2 characters' }, values }if (!email.includes('@')) return { errors: { email: 'Invalid e-mail' }, values }try {const user = await registerUser({ name, email })return { message: `Welcome, ${user.name}!` }} catch (e) {return { errors: { email: (e as Error).message }, values } // an error from the server at the e-mail field}}function Signup() {// [the last result, the function for <form action>, is it running?] = useActionState(action, initial result)const [state, formAction, isPending] = useActionState(signup, {})return (<form action={formAction}><input name="name" defaultValue={state.values?.name} />{state.errors?.name && <p>{state.errors.name}</p>}<input name="email" defaultValue={state.values?.email} />{state.errors?.email && <p>{state.errors.email}</p>}<SubmitButton />{state.message && <p>{state.message}</p>}</form>)}
What happens after clicking "Sign up":
preventDefault) and calls signup(previousState, formData).isPending is true – the "processing" sign is lit above the counter.state and the component re-renders.values, and after an error the fields get them back through defaultValue.useActionState is really useReducer from Hooks 03 for forms: the action gets the previous state and an "event" (the filled-in form) and returns a new state – it just may be asynchronous.
import { useFormStatus } from 'react-dom'function SubmitButton() {const { pending } = useFormStatus() // is the form this button is in being submitted?return <button disabled={pending}>{pending ? 'Signing up…' : 'Sign up'}</button>}
useFormStatus reads the state of the nearest parent <form>. Only whoever stands at the counter sees the sign – so it must be in a component inside the form, not in the one that renders the <form>. The reward is a button you put into any form and that knows by itself the form is being submitted.
What you see: The sign-up form from the example. The action checks the fields, calls the fake API (it takes about a second) and returns errors or a message. The button is a separate component with useFormStatus. At the bottom you see the value of isPending.
Try it:
@taken.com. While waiting, the button switches to "Signing up…" and isPending to true. Then an error from the server appears.The takeaway: React handles waiting, errors, double-click protection and clearing. You write only what matters: what should happen with the form.
Loading the interactive part…
A form that "works" isn't yet a form that's pleasant to use. This is the list of things checked in practice in every code review:
<form action={formAction}><label htmlFor="email">E-mail</label> {/* 1. every field has a label */}<inputid="email"name="email" // 2. name – otherwise it's not in FormDatatype="email" // 3. the right type (phone keyboard)autoComplete="email" // 4. the browser offers a saved e-mailrequireddefaultValue={state.values?.email} // 5. after an error, give back what the user wrotearia-invalid={state.errors?.email ? true : undefined} // 6. a screen reader knows the field is wrongaria-describedby="email-error" // and reads the message with it/>{state.errors?.email && <p id="email-error">{state.errors.email}</p>} {/* 7. the error at the field */}<SubmitButton /> {/* 8. the button disabled while submitting */}</form>
aria-invalid and aria-describedby are attributes for screen readers (programs that read the page aloud to blind people): the first says "this field is wrong", the second points through an id to the text with the message. A user who can't see the page learns the same as one who sees the red message.
A waiter puts your order on the bill as soon as you say it – they don't wait for the kitchen to confirm the ingredients are there. In most cases they are. And when something exceptionally runs out, they come back and cross the item off the bill.
Optimistic UI works the same way. When: for actions that almost always succeed (a like, adding to a cart, sending a message) you show the result at once and the server confirms in the background. When it fails, the change is reverted.
import { startTransition, useOptimistic, useState } from 'react'function LikeButton() {const [likes, setLikes] = useState(10) // confirmed by the serverconst [optimisticLikes, addOptimistic] = useOptimistic(likes, // the real value(current, delta: number) => current + delta, // how to "guess" the result)function like() {startTransition(async () => { // see the FAQ belowaddOptimistic(1) // 1) show +1 at oncetry {await likePost(1) // 2) wait for the server (likePost = a function of the fake API)setLikes((l) => l + 1) // 3a) confirm the real state} catch {// 3b) set nothing – the guess disappears by itself when the action ends}})}return <button onClick={like}>❤️ {optimisticLikes}</button>}
useOptimistic keeps two numbers side by side: the reality (what the server confirmed) and the guess (what you show the user for now). Let's take the call apart piece by piece:
likes is the real value – an ordinary state from useState. While no action is running, useOptimistic shows exactly that.current) and whatever you send it (delta), and returns the new value. It's the same idea as the reducer of useReducer from lesson Hooks 03: "old value + what happened → new value". Here: 10 + 1 → 11.useState: optimisticLikes is the value you display (the guess during an action, the reality otherwise), and addOptimistic is the function that starts a guess. Whatever you pass it (1) reaches the function from point 2 as delta.startTransition, see the FAQ below). As soon as the action ends, React throws the guess away and optimisticLikes equals likes again. If the server succeeded, likes is already 11, so the user notices no change. If it failed, likes stayed at 10 and the number on the button goes back – without a single line of "undo" code.| Moment | likes (reality) | optimisticLikes (shown) |
|---|---|---|
| before the click | 10 | 10 |
| right after the click | 10 | 11 |
| the server confirmed | 11 | 11 |
| …or the server failed | 10 | 10 – the guess disappeared |
The table reads top to bottom like a timeline: the middle column is the real state, the right one what the user sees.
What you see: A button with the number of likes and next to it the number confirmed by the server. The server answers in 0.7 s and fails in 25 % of cases.
Try it:
The takeaway: The user sees the result at once. The real state changes only by the server's answer, and on an error the guess reverts by itself.
Loading the interactive part…
You'll come back to optimistic changes in lesson Advanced React 08. There the server data is held by the TanStack Query library, and the same idea – show it at once, undo it on an error – is done with useMutation, so the change shows in every component that displays that data.
This section puts the lesson together into a template to come back to when you write your own form. You'll find the same pattern in the Cheat sheets on the React tab.
name.// the file src/components/ContactForm.tsximport { useActionState } from 'react'import { useFormStatus } from 'react-dom'// 1. WHAT THE ACTION RETURNS – the result from the filing officeinterface State {// errors at the fields. Record<'email' | 'message', string> = an object with the properties email and message, both text;// Partial<…> makes them optional – an error is there only for a field that's wrongerrors?: Partial<Record<'email' | 'message', string>>values?: { email: string; message: string } // what the user filled in – after an error it goes back into the fieldsdone?: boolean // true = the message was sent}// 2. THE ACTION – gets the previous result and the filled-in form, returns a new result// _prev = the previous result; we don't need it here and the leading underscore says soasync function send(_prev: State, formData: FormData): Promise<State> {// read the fields by name; String(… ?? '') = always text, trim = without spaces at the endsconst values = {email: String(formData.get('email') ?? '').trim(),message: String(formData.get('message') ?? '').trim(),}// the rules: each error is written to the field it concernsconst errors: State['errors'] = {} // State['errors'] = the type of the errors property of Stateif (!values.email.includes('@')) errors.email = 'Invalid e-mail'if (values.message.length < 10) errors.message = 'Write at least 10 characters'// Object.keys (lesson JavaScript 03) = an array of property names; empty = no errorif (Object.keys(errors).length > 0) return { errors, values } // errors → return the values tootry {await sendMessage(values) // sendMessage = a made-up function that sends the message to the serverreturn { done: true }} catch (e) {return { errors: { email: (e as Error).message }, values } // an error from the server at the e-mail field}}// 3. THE BUTTON – a separate component, so it can read the state of the form it's infunction SubmitButton() {const { pending } = useFormStatus() // is the parent form being sent?return <button disabled={pending}>{pending ? 'Sending…' : 'Send'}</button>}// 4. THE FORMexport function ContactForm() {// [the last result, a function for <form action>] – the initial result is an empty objectconst [state, formAction] = useActionState(send, {})if (state.done) return <p>Thanks, we'll be in touch.</p> // after success, a thank-you instead of the formreturn (<form action={formAction}><label>{/* name = the key in FormData; defaultValue = after an error, give back what the user wrote */}<input name="email" type="email" required autoComplete="email" defaultValue={state.values?.email} /></label>{state.errors?.email && <p className="field-error">{state.errors.email}</p>} {/* the error at the field */}<label>Message<textarea name="message" required defaultValue={state.values?.message} /></label>{state.errors?.message && <p className="field-error">{state.errors.message}</p>}<SubmitButton /></form>)}// use in a parent: <ContactForm />
<label>) and a name.type, autoComplete and required where it makes sense.Connect the text field to state so that it's controlled.
Task is in the comments in the code below – at the top of the file and at the places marked TODO.
row, stack, card, list, btn, input or muted are the course's ready-made styles in src/styles.css (row = side by side, stack = stacked, card = bordered box, muted = grey text).Loading the interactive part…
The first challenge is a controlled form (section 1) that behaves well: errors show only after leaving a field. The second combines sections 2 and 3 – a form without a single onSubmit and a comment that appears before the server saves it. For every form, first answer the three questions from section 4.
The clerk over your shoulder, but considerate: they don't point out an error before you leave the field. What exactly the form should do is in the comments in the code.
Medium and hard challenges unlock once you sign in. Like the whole course, they are free – just an e-mail, no password and no payment.
A modern form without a single onSubmit and without hand-made loading state. What should happen is in the comments in the code.
Medium and hard challenges unlock once you sign in. Like the whole course, they are free – just an e-mail, no password and no payment.
required, type, minLength, pattern, autoComplete) give checking for free – but the server checks again.<form action={fn}> handles waiting, double clicks and clearing; useActionState returns the result, useFormStatus is the sign for the button.name, the error at the field, the values after an error, a disabled button while submitting. The rules belong in a schema (Zod), big forms in React Hook Form.