Sub topic 3
The useActionState hook: arguments and return values
This chapter covers the shape of useActionState: what you pass in and what you get back. It assumes you know React function components, useState, the browser FormData API, and async functions. It also assumes you are on React 19 or later, where the hook is exported from react.
What the hook does
A form submission produces a result: a success message, a list of field errors, or an updated record. With useState you collect that result by hand. You write a submit handler, call event.preventDefault(), read the fields, set a loading flag, await the request, and then set the result in a try/finally.
useActionState replaces that routine with one call. You give it a function that handles a submission and returns the next state. The hook gives back the current state, a function to put on the form, and a pending flag. React tracks the in-flight work and the latest result for you.
The call signature
const [state, formAction, isPending] = useActionState(action, initialState, permalink?);| Argument | Required | Meaning |
|---|---|---|
| `action` | Yes | The function that runs on each submission. It receives the previous state first, then the arguments the caller supplies. It returns the next state, or a promise of it. |
| `initialState` | Yes | The value of `state` before any submission. It can be any serializable-looking value: an object, an array, a number, or `null`. |
| `permalink` | No | A URL string. It only matters when `action` is a server function and the form is submitted before client JavaScript has loaded. A later chapter covers it. |
Pass null or an empty object as initialState if you have nothing to show yet. Do not pass undefined. Components that read state.error would then throw on the first render.
The return values
The hook returns an array of three items, which you normally destructure.
| Position | Usual name | Meaning |
|---|---|---|
| 0 | `state` | `initialState` until the first submission finishes. After that, whatever the most recent action returned. |
| 1 | `formAction` | A new action function you pass to `<form action={...}>`. Calling it runs your `action` with the right arguments. |
| 2 | `isPending` | `true` while a submission is running, `false` otherwise. |
isPending was added alongside the hook in React 19. Older code and articles may show a two-item array, or the earlier name useFormState from react-dom. Treat those as outdated.
The formAction you get back is not your original function. React wraps it so that it can manage state, queue repeated calls, and mark the work as a transition. Always give the form the returned formAction, not the function you wrote.
A minimal example
This component greets the user and counts how many submissions have succeeded.
import { useActionState } from "react";
async function greet(prevState, formData) {
const name = String(formData.get("name") ?? "").trim();
// Simulate a slow request.
await new Promise((resolve) => setTimeout(resolve, 500));
if (!name) {
return { ...prevState, message: "Please enter a name." };
}
return {
greetings: prevState.greetings + 1,
message: `Hello, ${name}!`,
};
}
export function GreetForm() {
const [state, formAction, isPending] = useActionState(greet, {
greetings: 0,
message: "",
});
return (
<form action={formAction}>
<input name="name" type="text" />
<button type="submit" disabled={isPending}>
{isPending ? "Greeting..." : "Greet"}
</button>
<p>{state.message}</p>
<p>Greetings so far: {state.greetings}</p>
</form>
);
}The component never calls setState, and the form has no onSubmit. React calls greet when the form is submitted, waits for the promise, and re-renders with the returned object as state. The counter works because prevState carries the old count into the next call.
How state flows between submissions
The first argument to your action is not a snapshot from render time. It is the result of the last completed action, or initialState if there has not been one.
The state is a chain, and each result feeds the next call. This is why you can build on the previous value (increment a counter, append to a list) without reading it from a closure that may be stale.
The arguments your action receives
When the form calls it, action gets two arguments.
prevState: the current state value, as described above.formData: aFormDataobject built from the form's named fields. If a button has anameandvalue, that pair is included when that button submits the form.
Read values with formData.get("fieldName"). It returns a string, a File, or null, so convert deliberately, as in String(formData.get("name") ?? "").
The action may be async or synchronous. If it returns a promise, React waits for it. The value that promise resolves to becomes the next state. Return a value on every code path. An early return; sets the state to undefined, which breaks the next render if you read state.message.
The state can be any shape. This version uses a number and ignores the form entirely:
import { startTransition, useActionState } from "react";
async function increment(prevCount, amount) {
return prevCount + amount;
}
export function Counter() {
const [count, dispatch, isPending] = useActionState(increment, 0);
return (
<button
disabled={isPending}
onClick={() => startTransition(() => dispatch(1))}
>
Count: {count}
</button>
);
}Here the second argument is amount, not FormData. Whatever you pass to the returned function arrives after prevState. A form passes FormData, and your own code can pass anything. Because this call happens outside a form action, it must be wrapped in startTransition. A later chapter on dispatching from event handlers explains why.
Rules for initial state
initialStateis used only until an action has run. Changing the value you pass on a later render has no effect.- On the first render,
stateis exactly the value you passed in, so the first render shows your defaults. - With server rendering, the initial state must be something React can serialize if the action is a server function. Plain objects, arrays, strings, numbers, and booleans are safe. Class instances and functions are not.
What happens when the action throws
If your action throws or its promise rejects, no new state is produced. React rethrows the error during rendering, so the nearest error boundary handles it. Queued submissions that have not yet run are cancelled.
That makes thrown errors a poor fit for problems the user can fix, such as an empty field or a taken username. Return those as part of the state so the form stays on screen with the message. Reserve throwing for failures that should replace the UI, such as a lost connection. The chapter on validation develops this in detail.
Common mistakes with the signature
- Wrong argument order. Writing
async function action(formData)and wondering whyformData.getis not a function. The first argument is always the previous state. - Passing the original action to the form. Writing
<form action={greet}>skips the hook entirely. Use the returnedformAction. - Ignoring the third value. Forgetting
isPendingmeans users can double-click while a request is in flight. Disable the button or show a status. - Returning nothing. A code path that returns
undefinedmakesstateundefined on the next render. - Expecting the state to reset. The state persists across submissions. Return a cleared object explicitly if you want a clean slate after success.
Exercise
A teammate writes const [state, formAction] = useActionState(save, null); with async function save(formData) { return { ok: true }; }, then renders <form action={formAction}>. The component shows state as { ok: true } but formData.get("title") throws "formData.get is not a function". What is wrong, and what is the fix? Also name the value that is missing from the destructuring if they want to disable the submit button during the request.
Show answer
The action's first parameter is the previous state, not the FormData. On the first submission formData is actually null, the initial state, so .get fails. Change the signature to async function save(prevState, formData). The missing value is the third item, isPending: const [state, formAction, isPending] = useActionState(save, null);, used as disabled={isPending} on the button.