Forms & Actions
Form Actions, async functions, pending UI, optimistic updates, and validation without a pile of local loading state. · 4 lessons · click a card to expand
Part of the React 16 → 19.3 evolution reference. Expand a card, then use chapter links in the sidebar.
Core APIs were introduced in React 19. This chapter is the forms playbook with three distinct product examples per idea. Server Functions need a bundler — labeled [RSC] / [framework].
Form Actions
1 item01A form action can be a functionReact 19
<form action={fn}> runs fn(formData) as an Action. Progressive enhancement: without JavaScript, a server action URL can still submit; with JS, React intercepts and stays on the page.action="/url" and method="POST". React 19 lets action be a function.async function createTicket(formData) {
const title = formData.get("title");
await api.tickets.create({ title });
}
function TicketForm() {
return (
<form action={createTicket}>
<input name="title" required />
<button type="submit">Open ticket</button>
</form>
);
}import { useActionState } from "react";
async function createTicket(prev, formData) {
const title = String(formData.get("title") || "").trim();
await new Promise((resolve) => setTimeout(resolve, 400));
if (!title) return prev;
return [...prev, { id: String(prev.length + 1), title }];
}
export default function TicketForm() {
const [tickets, formAction, isPending] = useActionState(createTicket, []);
return (
<div>
<form action={formAction}>
<input name="title" placeholder="Ticket title" />
<button type="submit" disabled={isPending}>
{isPending ? "Opening…" : "Open ticket"}
</button>
</form>
<ul>
{tickets.map((ticket) => (
<li key={ticket.id}>{ticket.title}</li>
))}
</ul>
</div>
);
}Click Run to render this example.
No onSubmit, no preventDefault for the happy path. Inputs can stay uncontrolled (name=) which is how FormData works.
Why it was introduced?
Controlled forms + useState for every field + pending + error is a lot of React for what HTML already modeled. Actions reconnect React to native forms.
Before React 19
const [title, setTitle] = useState("");
const [pending, setPending] = useState(false);
async function onSubmit(e) {
e.preventDefault();
setPending(true);
await api.tickets.create({ title });
setPending(false);
setTitle("");
}With Form Actions
The browser builds FormData. React runs the function as a transition. Empty the form yourself on success if you need to (or use useActionState to reset).
How it works
- User submits.
- React calls your function with
FormData(and, withuseActionState, previous state). useFormStatusin children seespending.- If this is a Server Function, the bundler POSTs to a server endpoint [framework]. If it is a client function, it just
awaits yourfetch.
Real-world examples
1. Support ticket (SaaS) — title + body, uncontrolled fields, action={createTicket}.
2. Newsletter footer — email only; works even before JS if you point action at a real URL and a server.
3. Admin “rename project” — one field modal form; pending disables Save via useFormStatus.
When should I use function actions?
Mutations from forms. Especially with useActionState for error text.
When should I NOT?
Instant search filters (not a mutation). Complex wizards that are 100% controlled and already built — you can migrate incrementally.
Common mistakes
- Missing
nameattributes - Putting
actionon a<div>(must be<form>) buttonwithouttype="submit"inside nested buttons
Related APIs
useActionState, useFormStatus, HTML formAction on a button (per-button actions)
Interview notes
actioncan be a function in 19.- Uncontrolled +
FormDatais the native path. - Server Functions are extra (framework).
formAction={saveDraft} while the form’s action={publish}.formActions, shared fields.Async Actions and pending UI
1 item02Pending UI is built into ActionsReact 19
useState(false) for submit pending if you already have an Action.| API | Where |
|---|---|
useTransition → isPending | You called startTransition(async () => …) |
useActionState → third element | Form bound to that hook |
useFormStatus → pending | Child of <form> |
Real-world examples
1. Checkout “Place order” — useFormStatus on the button; spinner; aria-busy on the form.
2. Settings: upload avatar — isPending from useActionState; disable file input too (avoid double file send).
3. Chat: send on Enter — not a <form>? Use startTransition(async () => send(text)) and disable the composer with isPending.
import { useActionState } from "react";
async function placeOrder(_prev, formData) {
await new Promise((resolve) => setTimeout(resolve, 700));
return { orderId: "ORD-" + String(formData.get("sku") || "demo") };
}
export default function CheckoutForm() {
const [state, formAction, isPending] = useActionState(placeOrder, null);
return (
<form action={formAction} aria-busy={isPending}>
<input name="sku" defaultValue="mug-1" />
<button disabled={isPending}>{isPending ? "Placing…" : "Place order"}</button>
{state?.orderId ? <p role="status">Placed {state.orderId}</p> : null}
</form>
);
}Click Run to render this example.
Validation
Client HTML: required, type="email", minLength. This runs before the Action.
<input name="email" type="email" required />Server / Action-level:
async function register(prev, formData) {
const email = String(formData.get("email") || "");
if (!email.includes("@")) return { error: "Enter a valid email" };
await api.register(email);
return { error: null };
}Do both: HTML for instant UX, Action return value for business rules (email taken).
When should I add extra pending state?
When pending is per-row in a list (not the whole form). Then a row-level useTransition or optimistic flag is clearer than one form status.
aria-busy={pending} on the form helps assistive tech.disabled={pending} for UX).Optimistic UI in forms
1 item03Optimistic updates belong next to the ActionReact 19
useOptimistic). For forms, show the next list immediately, then let the Action confirm.useOptimistic + form Action.function Todos({ todos, addTodo }) {
const [optimisticTodos, addOptimistic] = useOptimistic(todos, (current, title) => [
...current,
{ id: "tmp", title, sending: true },
]);
async function action(formData) {
const title = formData.get("title");
addOptimistic(title);
await addTodo(title);
}
return (
<>
<ul>
{optimisticTodos.map((t) => (
<li key={t.id} style={{ opacity: t.sending ? 0.6 : 1 }}>
{t.title}
</li>
))}
</ul>
<form action={action}>
<input name="title" />
<button>Add</button>
</form>
</>
);
}import { useOptimistic, useState } from "react";
export default function OptimisticTodos() {
const [todos, setTodos] = useState([
{ id: "1", title: "Read the Action docs" },
]);
const [optimisticTodos, addOptimistic] = useOptimistic(
todos,
(current, title) => [...current, { id: "tmp-" + title, title, sending: true }],
);
async function action(formData) {
const title = String(formData.get("title") || "").trim();
if (!title) return;
addOptimistic(title);
await new Promise((resolve) => setTimeout(resolve, 500));
setTodos((prev) => [...prev, { id: String(prev.length + 1), title }]);
}
return (
<div>
<ul>
{optimisticTodos.map((todo) => (
<li key={todo.id} style={{ opacity: todo.sending ? 0.6 : 1 }}>
{todo.title}
</li>
))}
</ul>
<form action={action}>
<input name="title" placeholder="New todo" />
<button>Add</button>
</form>
</div>
);
}Click Run to render this example.
Real-world examples
1. Todo / issue tracker — new row appears grayed until the server id exists.
2. Chat composer — message at the bottom instantly.
3. E-commerce cart drawer — qty stepper optimistic; revert if inventory fails.
When should I NOT be optimistic?
Checkout pay, “delete account”, anything legally/financially sensitive.
Common mistakes
- Using
Date.now()as a key that changes on confirm (remounts the row) - Forgetting the item is
sendingin CSS so users double-add
tmp key; when todos from the server updates, useOptimistic resets to the real list.Validation playbook
1 item04Combine HTML, Action returns, and (optionally) a schemaReact 19
| Layer | Good for | Example |
|---|---|---|
| HTML attributes | Format / required | type="email", min="1" |
| Action return | Business rules, i18n errors | { fieldErrors: { coupon: "Expired" } } |
| Schema (Zod, etc.) | Shared client/server types | Parse formData once |
async function checkout(prev, formData) {
const qty = Number(formData.get("qty"));
if (qty < 1) return { fieldErrors: { qty: "Minimum 1" }, ok: false };
try {
await api.checkout({ qty });
return { ok: true, fieldErrors: {} };
} catch (e) {
return { ok: false, fieldErrors: { form: e.message } };
}
}Render:
{state.fieldErrors.qty ? <p>{state.fieldErrors.qty}</p> : null}Real-world examples
1. Coupon field — HTML cannot know “expired”; Action can.
2. Signup username uniqueness — only the server knows.
3. Quantity vs stock — Action returns remaining stock error.
When should I use a full form library?
Huge wizards, multi-step with dependent fields, already-on-React-Hook-Form codebases. React 19 Actions do not obsolete RHF; they obsolete pending boilerplate for simple forms.
fieldErrors with the same name as the input for a11y (aria-invalid, aria-describedby).{ fieldErrors } from a fake Action and wire aria-describedby to the error id from useId.