Sub topic 2
Designing the State Shape with `useActionState`
Assume you know React function components, hooks, HTML forms, FormData, and asynchronous JavaScript. useActionState connects a form submission to state returned by an action function.
Choose state for the UI
The state should contain the information the component must render after submission. A useful shape commonly includes:
ok: whether the operation succeeded.error: a message for the user, ornull.- Submitted values that should remain visible.
The action receives the previous state first and the submitted FormData second. It returns the next state.
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 address.", 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}>
<label>
Email
<input name="email" defaultValue={state.email} />
</label>
<button type="submit" disabled={isPending}>
{isPending ? "Subscribing..." : "Subscribe"}
</button>
{state.error && <p role="alert">{state.error}</p>}
{state.ok && <p>Thanks for subscribing.</p>}
</form>
);
}The second argument to useActionState is the initial state. Keep its fields consistent with every state returned by the action.
Pending feedback with `isPending`
The third returned value, isPending, is true while the action runs. Disable submission controls and change their labels so users receive immediate feedback. Actions run in a transition, which lets React track this pending work without manual loading state.
Validation errors and form reset
When a form action completes, React resets uncontrolled form fields. Returning the submitted value in state and passing it to defaultValue lets invalid input appear again. On success, return an empty value so the next render displays a cleared field.
The flow is:
Exercise
Why does the invalid branch return email in its state?
Show answer
React resets uncontrolled fields after the action, so rendering state.email through defaultValue preserves what the user typed.