Sub topic 3
Reading Form Status with `useFormStatus`
Assume React 19, function components, hooks, HTML forms, FormData, and asynchronous JavaScript. This chapter focuses on the tools around useActionState, rather than its basic setup.
Reading status in child components with `useFormStatus`
useFormStatus reads the status of the nearest parent <form>. The component using it must render inside that form. It cannot read the status of a form from the same component that creates the form.
import { useFormStatus } from "react-dom";
import { useActionState } from "react";
function SubmitButton({ children }) {
const { pending } = useFormStatus();
return (
<button type="submit" disabled={pending}>
{pending ? "Saving..." : children}
</button>
);
}
async function saveTitle(previous, formData) {
const title = String(formData.get("title") ?? "").trim();
await new Promise((resolve) => setTimeout(resolve, 500));
return { title, error: title ? null : "A title is required." };
}
export function TitleForm() {
const [state, formAction] = useActionState(saveTitle, {
title: "",
error: null,
});
return (
<form action={formAction}>
<input name="title" defaultValue={state.title} />
<SubmitButton>Save</SubmitButton>
{state.error && <p role="alert">{state.error}</p>}
</form>
);
}This keeps reusable buttons independent of an isPending prop.
Dispatching from event handlers
The returned dispatcher also accepts values other than FormData. When calling it outside a form action, wrap the call in startTransition.
import { startTransition, useActionState } from "react";
async function increment(previousCount, amount) {
return previousCount + amount;
}
export function Counter() {
const [count, dispatch, pending] = useActionState(increment, 0);
return (
<button
disabled={pending}
onClick={() => startTransition(() => dispatch(1))}
>
Count: {count}
</button>
);
}Queued submissions
Repeated dispatches run through the action system in order. Do not assume that several submissions finish in the order their network requests would normally finish. Design the returned state so each action can safely build on the previous state. Disable controls when duplicate submissions would be harmful.
Server functions and progressive enhancement
With a supported framework, a server function can be passed to useActionState. Its optional third argument is a permalink. Before client JavaScript loads, the browser can submit to that URL and render the result there. The URL should identify a page that renders the same form and action.
Pairing with `useOptimistic`
useOptimistic shows an expected result immediately while the action runs. Use it for responsive interfaces such as adding a comment. Replace the optimistic value with the action's returned state when the request succeeds, and handle failure so temporary data does not remain misleading.
Common pitfalls and error handling
- Put
useFormStatusin a child component inside the form. - Return expected validation failures as state instead of throwing.
- Catch expected network or server errors and return an error field.
- Use an error boundary for unexpected failures.
- Remember that uncontrolled form fields may reset after submission. Return submitted values in state when users need to correct them.
Exercise
Why does a submit button component need to be rendered inside the form to use useFormStatus?
Show answer
The hook reads context from its nearest parent form, so a component outside that form cannot observe its pending state.