Skip to content
Tutorials Center
My learning

Topics

Lesson 46 of 132 ยท Forms and Actions

useActionState

Learn the React 19 useActionState hook - the (previousState, formData) signature, isPending, state shape for results and errors, queued actions, and when to choose useReducer.

A form action does work, and the page then needs to know what happened: did it succeed, which field failed, what should the user see? In Form Actions in React 19 the action had to push its result into state by hand, and we saw that a manual "saving" flag does not even display while an async action runs. React 19's answer is one hook that ties the three things together: the action, its latest result, and whether it is still running.

JSX
const [state, formAction, isPending] = useActionState(action, initialState);

You hand it your action and a starting value. It gives back the current state (the last value your action returned), a wrapped action to put on <form action={...}>, and an isPending boolean. Think of it as useReducer for things that happen on a form submission and may take time. This lesson explains the signature, shows a full sign-up form against a simulated API, covers the state shape that works well, explains how actions queue, and compares the hook with useReducer.

The signature: an action that receives the previous state

The function you give to useActionState is slightly different from a plain form action. It gets two arguments: the previous state first, then the FormData. Whatever it returns becomes the next state.

JavaScript
async function myAction(previousState, formData) {
  // do work...
  return nextState;
}

The simplest possible example keeps a running total. The state is a number, and each submission adds the amount from the form.

State flows from one action to the next

Press Add three times (wait for each to finish) and the total goes 5, 10, 15. The console logs start: adding 5 to 0, then start: adding 5 to 5, and so on: the previousTotal argument is exactly what the last call returned. Unlike a manual flag, isPending does show up: the button reads "Adding..." and is disabled while the promise is running, because useActionState is wired into React's transition machinery.

Three things to remember about the three return values:

  • state starts as the initialState you passed and is replaced by whatever each run of the action returns. It is not reset when the form resets.
  • formAction is a new function you pass to <form action> (or to a button's formAction). Do not call your original function there; the wrapped one is what supplies previousState.
  • isPending is true from the moment an action is dispatched until all queued actions have finished and the new state is rendered.

A realistic form: results, errors and the user's input

Real actions produce more than a number. A good habit is to return one object with a stable shape that the component can render without guessing. Here is a shape that works for most forms:

JavaScript
{
  status: 'idle' | 'error' | 'success',
  message: '',          // text for a banner at the top
  errors: {},           // { fieldName: 'message' }
  values: {},           // what the user submitted, to put back into the fields
}

Returning values solves the problem from the previous lesson: after a failed submit React resets the form, so you feed the user's input back through defaultValue. The demo below validates on the "server" (a simulated API with a delay), handles an expected failure ([email protected] is already registered), and survives an unexpected one ([email protected] makes the fake network throw).

A sign-up form with useActionState

Try these in order: submit empty (two field errors, "Please fix the highlighted fields."); type Ada and [email protected] (after 150 ms the email error appears and your input is still there); use [email protected] (the catch block returns the "Could not reach the server" banner, and nothing crashes); finally a valid pair, which clears the form and shows the welcome message.

Several design choices carry the whole pattern:

  1. Expected failures are return values, unexpected failures are caught. The action never throws for validation or "email taken". The try/catch converts a thrown network error into the same state shape, so the UI has one way to render problems. Without it, a thrown error would reach an error boundary and, with none, unmount the app.
  2. defaultValue from state restores input. After the reset React applies the new defaultValue, so the fields show what the user typed. On success we return empty values, so the form is clear.
  3. The message and errors live in state, not in event handlers. The component has no useState at all; the action is the single place where results are decided.
  4. aria-invalid and a role on the banner keep the form usable with a screen reader (see Form Validation for the full accessibility checklist).

If a field keeps showing a stale value after a reset, remember that a reset returns an input to its defaultValue. Putting the submitted value in defaultValue is what makes it come back. If the value must survive without a re-render (a long text area), a controlled field is still a good choice.

Actions run one at a time

What if the user submits twice quickly, or your code dispatches several actions? React queues them and runs them one after another, in order. Each action receives the state returned by the previous one. That makes sequences predictable (no two runs race to update the same state), and it is the key difference from firing independent fetch calls.

Queued actions and the previous state

Press Submit three times. After about 400 ms the log reads start job (total was 0), end job, start job (total was 1), end job, start job (total was 2), end job. The runs did not overlap, and each saw the previous total. While any of them is running Pending stays true; it turns false once, when the last one is done.

Because of queuing, avoid actions that you expect to be cancelled by a newer one (like a search box where only the latest query matters). For that, use transitions and a cancel-aware fetch, or keep the form-submit pattern for operations that should each run.

Using it without a form

useActionState is made for forms, but the wrapped function is just a function, and you can call it yourself. The rule is that React must know it is an Action, so call it inside startTransition (or give it to an action / formAction prop). Otherwise React cannot track isPending, and warns you. Here is the real message.

Dispatching outside a transition (fails on purpose)

Press the button and the console prints an error starting with An async function with useActionState was called outside of a transition. This is likely not what you intended (for example, isPending will not update correctly). and ending with Either call the returned function inside startTransition, or pass it to an action or formAction prop. The fix is a one-liner: onClick={() => startTransition(() => dispatch())}, with startTransition imported from react. Note that here the action's first parameter is the previous state alone, because no FormData is passed; whatever you give to dispatch becomes the second argument.

useActionState or useReducer?

They look alike (state plus a function that computes the next state), and the choice is easy once you see the difference.

useReducer useActionState
Update function Pure, synchronous (state, action) => state May be async, may call APIs and have side effects
Triggered by dispatch(action) anywhere A form submission, a formAction, or a call inside a transition
Pending state None built in isPending built in, integrated with transitions
Queueing Updates apply immediately and in order Each action waits for the previous one to finish
Best for UI state machines: a todo list, a wizard, counters (see reducers) The result of submitting something: a save, a login, a post

A good rule: if the work is a pure calculation on local state, use a reducer. If the work "goes out" (network, database) and the answer should appear as state, use useActionState. You can combine them: keep a reducer for the form's editing state and use an action for the submit.

Pitfalls professionals avoid

  • Do not mutate previousState. Return a new object, as with any state.
  • Keep the state serialisable and small. A File or a large list in the result makes re-renders heavy; return ids or messages.
  • Pass the wrapped action, not the original. action={signUp} instead of action={formAction} skips the hook and loses state and isPending.
  • Do not put secrets in returned state. Anything you return is rendered in the browser.
  • Reset deliberately. The hook's state survives form resets. Return an explicit "cleared" state on success (as the sign-up form did).
  • An optional third argument, permalink, exists for server-rendered forms in frameworks (it names the page to submit to when JavaScript has not loaded). It has no effect in a client-only app.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What are the parameters of the function you pass to useActionState (for a form)?

    The first argument is the state returned by the previous run (or the initial state), the second is the FormData of the submission.
  2. 2. Which values does useActionState return, in order?

    You get the current state, the wrapped action to pass to the form, and the pending flag.
  3. 3. A user submits a form three times in quick succession. What happens to the actions?

    useActionState queues actions so they never overlap. Each receives the state returned by the one before it.
  4. 4. How do you keep what the user typed after the action returns a validation error?

    The form is reset after submit, so the action returns the values in its state and the inputs use them as defaultValue to show them again.
  5. 5. Why does calling the returned action from a plain onClick log an error?

    React warns that an async action was dispatched outside a transition. Wrap the call in startTransition or pass it to a form's action or a button's formAction.

Summary

  • useActionState(action, initialState) returns [state, formAction, isPending]; give formAction to <form action>.
  • The action receives (previousState, formData) and returns the next state; the state is the last returned value.
  • isPending works for async actions, unlike a manual flag set inside the action.
  • Return one object shape (status, message, errors, values); catch unexpected errors and turn them into the same shape.
  • Return the submitted values and use them as defaultValue to keep the user's input after a reset.
  • Actions are queued and run one at a time, each seeing the previous result.
  • Outside a form, call the wrapped function inside startTransition.
  • Use useReducer for pure local state logic and useActionState for the result of submitting something.

Next: useFormStatus and useOptimistic