React Reference ยท Performance and Concurrency Hooks
React useActionState hook
Reference for React useActionState: keep state that changes with the result of a form action, get a pending flag, and handle validation errors without effects.
useActionState connects a function (an action) to a piece of state. Each time the action runs, React calls it with the previous state and the submitted FormData; whatever it returns becomes the new state. You also get a wrapped action to give to <form action> and an isPending flag.
This replaces the old pattern of useState + onSubmit + loading and error flags with one hook. It is exported from react and replaces the earlier useFormState from react-dom that shipped in React canary builds.
const [state, formAction, isPending] = useActionState(action, initialState);
Try it
When you call the wrapped action yourself (not through a form), wrap the call in startTransition; the argument you pass is delivered as the second parameter.
Syntax
const [state, formAction, isPending] = useActionState(action, initialState, permalink?); // action: (previousState, payload) => newState | Promise<newState>
| Name | Description |
|---|---|
action |
Called with the previous state and the payload (a FormData when used as a form action). May be async. |
initialState |
State before the first run. Ignored afterwards. |
permalink |
Optional URL for server-rendered forms so the form works before JavaScript loads. |
Returns: a three-item array: the current state, a formAction function to pass to <form action> (or to call inside a transition), and isPending (boolean).
Edge cases: if the action throws, the error goes to the nearest error boundary and the state is not updated. Calls are queued and run one after another, each seeing the state returned by the previous.
Usage notes
- Return, don't set. The action's return value is the next state. Return an error object instead of throwing for validation problems the user can fix.
- Uncontrolled inputs reset. After a successful form action React resets uncontrolled fields. Use
defaultValuefrom the returned state to keep what the user typed after an error. - Sequential, not parallel. Rapid submissions queue; this keeps state consistent but means a slow action delays later ones.
- Not for plain input state. Use
useStatefor things that change while typing. - Server Functions. The action can be a Server Function (
"use server"), and with apermalinkthe form can submit before hydration. - With optimistic UI: call
useOptimisticsetters inside the action. - Read pending state in children with
useFormStatus.