Sub topic 1
Forms as Actions in React 19
Prerequisites
You should know function components, React hooks, HTML forms, the FormData API, and JavaScript promises. This chapter assumes React 19.
Forms as Actions in React 19
A form action is a function React runs when a form submits. React 19 lets you connect that function directly to a form's action prop. The function receives the submitted fields and can return the result of the submission.
useActionState connects the action's result to component state. This avoids separately tracking submitted values, errors, and loading state with several useState calls.
How Actions Run in Transitions
React runs actions in a transition, which is a render update that can happen without blocking urgent interactions. While the action is running, React exposes a pending status. You can use that status to disable the submit button or show progress.
The action may be asynchronous. React keeps the previous state available until the action returns its next state.
The `useActionState` Hook: Arguments and Return Values
The hook has this signature:
const [state, formAction, isPending] = useActionState(
action,
initialState,
permalink
);actionis the function React calls on submission.initialStateis the state before the first submission.permalinkis an optional URL used with server functions for progressive enhancement.stateis the latest value returned by the action.formActionis the action to pass to the form.isPendingistruewhile the action runs.
Writing the Action Function
The action receives the previous state first and the submitted FormData second. It must return the next state. The returned value can be an object, array, string, or another value that matches your state design.
import { useActionState } from "react";
async function subscribe(previous, formData) {
const email = String(formData.get("email") ?? "").trim();
if (!email.includes("@")) {
return { ok: false, error: "Enter a valid email.", email };
}
await fetch("/api/subscribe", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ email }),
});
return { ok: true, error: null, email: "" };
}
export function SubscribeForm() {
const [state, formAction, isPending] = useActionState(subscribe, {
ok: false,
error: null,
email: "",
});
return (
<form action={formAction}>
<input name="email" defaultValue={state.email} />
<button disabled={isPending}>
{isPending ? "Subscribing..." : "Subscribe"}
</button>
{state.error && <p role="alert">{state.error}</p>}
{state.ok && <p>Thanks for subscribing.</p>}
</form>
);
}Exercise
What are the first two arguments passed to an action used with useActionState?
Show answer
The previous state and the submitted FormData.