useActionState

useActionState is a React Hook that lets you update state with side effects using Actions.

const [state, dispatchAction, isPending] = useActionState(reducerAction, initialState, permalink?);

Reference

Call useActionState at the top level of your component to create state for the result of an Action.

import { useActionState } from 'react';

function reducerAction(previousState, actionPayload) {
  // ...
}

function MyCart({initialState}) {
  const [state, dispatchAction, isPending] = useActionState(reducerAction, initialState);
  // ...
}

See more examples below.

Parameters

  • reducerAction: The function to be called when the Action is triggered. When called, it receives the previous state (initially the initialState you provided, then its previous return value) as its first argument, followed by the actionPayload passed to dispatchAction.
  • initialState: The value you want the state to be initially. React ignores this argument after dispatchAction is invoked for the first time.
  • optional permalink: A string containing the unique page URL that this form modifies.
  • For use on pages with React Server Components with progressive enhancement.
  • If reducerAction is a Server Function and the form is submitted before the JavaScript bundle loads, the browser will navigate to the specified permalink URL rather than the current page's URL.

Returns

useActionState returns an array with exactly three values:

  1. The current state. During the first render, it will match the initialState you passed. After dispatchAction is invoked, it will match the value returned by the reducerAction.
  2. A dispatchAction function that you call inside Actions.
  3. The isPending flag that tells you if any dispatched Actions for this Hook are pending.

Caveats

  • useActionState is a Hook, so you can only call it at the top level of your component or your own Hooks. You can't call it inside loops or conditions. If you need that, extract a new component and move the state into it.
  • React queues and executes multiple calls to dispatchAction sequentially. Each call to reducerAction receives the result of the previous call.
  • The dispatchAction function has a stable identity, so you will often see it omitted from Effect dependencies, but including it will not cause the Effect to fire. If the linter lets you omit a dependency without errors, it is safe to do. Learn more about removing Effect dependencies.
  • When using the permalink option, ensure the same form component is rendered on the destination page (including the same reducerAction and permalink) so React knows how to pass the state through. Once the page becomes interactive, this parameter has no effect.
  • When using Server Functions, initialState needs to be serializable (values like plain objects, arrays, strings, and numbers).
  • If dispatchAction throws an error, React cancels all queued actions and shows the nearest Error Boundary.
  • If there are multiple ongoing Actions, React batches them together. This is a limitation that may be removed in a future release.

[!NOTE]

dispatchAction must be called from an Action.

You can wrap it in startTransition, or pass it to an Action prop. Calls outside that scope won’t be treated as part of the Transition and log an error on development mode.


reducerAction function

The reducerAction function passed to useActionState receives the previous state and returns a new state.

Unlike reducers in useReducer, the reducerAction can be async and perform side effects:

async function reducerAction(previousState, actionPayload) {
  const newState = await post(actionPayload);
  return newState;
}

Each time you call dispatchAction, React calls the reducerAction with the actionPayload. The reducer will perform side effects such as posting data, and return the new state. If dispatchAction is called multiple times, React queues and executes them in order so the result of the previous call is passed as previousState for the current call.

Parameters

  • previousState: The last state. Initially this is equal to the initialState. After the first call to dispatchAction, it's equal to the last state returned.

  • optional actionPayload: The argument passed to dispatchAction. It can be a value of any type. Similar to useReducer conventions, it is usually an object with a type property identifying it and, optionally, other properties with additional information.

Returns

reducerAction returns the new state, and triggers a Transition to re-render with that state.

Caveats

  • reducerAction can be sync or async. It can perform sync actions like showing a notification, or async actions like posting updates to a server.
  • reducerAction is not invoked twice in <StrictMode> since reducerAction is designed to allow side effects.
  • The return type of reducerAction must match the type of initialState. If TypeScript infers a mismatch, you may need to explicitly annotate your state type.
  • If you set state after await in the reducerAction you currently need to wrap the state update in an additional startTransition. See the startTransition docs for more info.
  • When using Server Functions, actionPayload needs to be serializable (values like plain objects, arrays, strings, and numbers).

[!INFO]

Why is it called reducerAction?

The function passed to useActionState is called a reducer action because:

  • It reduces the previous state into a new state, like useReducer.
  • It's an Action because it's called inside a Transition and can perform side effects.

Conceptually, useActionState is like useReducer, but you can do side effects in the reducer.


Usage

Adding state to an Action

Call useActionState at the top level of your component to create state for the result of an Action.

```js [[1, 7, "count"], [2, 7, "dispatchAction"], [3, 7, "isPending"]] import { useActionState } from 'react';

async function addToCartAction(prevCount) { // ... } function Counter() { const [count, dispatchAction, isPending] = useActionState(addToCartAction, 0);

// ... }


`useActionState` returns an array with exactly three items:

1. The &lt;CodeStep step={1}>current state&lt;/CodeStep>, initially set to the initial state you provided.
2. The &lt;CodeStep step={2}>action dispatcher&lt;/CodeStep> that lets you trigger `reducerAction`.
3. A &lt;CodeStep step={3}>pending state&lt;/CodeStep> that tells you whether the Action is in progress.

To call `addToCartAction`, call the &lt;CodeStep step={2}>action dispatcher&lt;/CodeStep>. React will queue calls to `addToCartAction` with the previous count.

```js src/App.js
import { useActionState, startTransition } from 'react';
import { addToCart } from './api';
import Total from './Total';

export default function Checkout() {
  const [count, dispatchAction, isPending] = useActionState(async (prevCount) => {
    return await addToCart(prevCount)
  }, 0);

function handleClick() {
    startTransition(() => {
      dispatchAction();
    });
  }

return (
    <div className="checkout">
      <h2>Checkout</h2>
      <div className="row">
        <span>Eras Tour Tickets</span>
        <span>Qty: {count}</span>
      </div>
      <div className="row">
        <button onClick={handleClick}>Add Ticket{isPending ? ' 🌀' : '  '}</button>
      </div>
      <hr />
      <Total quantity={count} />
    </div>
  );
}

```js src/Total.js const formatter = new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD', minimumFractionDigits: 0, });

export default function Total({quantity}) { return (

Total {formatter.format(quantity * 9999)}
); }


```js src/api.js
export async function addToCart(count) {
  await new Promise(resolve => setTimeout(resolve, 1000));
  return count + 1;
}

export async function removeFromCart(count) {
  await new Promise(resolve => setTimeout(resolve, 1000));
  return Math.max(0, count - 1);
}
.checkout {
  display: flex;
  flex-direction: column;
  gap: 12px;
  padding: 16px;
  border: 1px solid #ccc;
  border-radius: 8px;
  font-family: system-ui;
}

.checkout h2 {
  margin: 0 0 8px 0;
}

.row {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.row button {
  margin-left: auto;
  min-width: 150px;
}

.total {
  font-weight: bold;
}

hr {
  width: 100%;
  border: none;
  border-top: 1px solid #ccc;
  margin: 4px 0;
}

button {
  padding: 8px 16px;
  cursor: pointer;
}

Every time you click "Add Ticket," React queues a call to addToCartAction. React shows the pending state until all the tickets are added, and then re-renders with the final state.

[!INFO]

How useActionState queuing works

Try clicking "Add Ticket" multiple times. Every time you click, a new addToCartAction is queued. Since there's an artificial 1 second delay, that means 4 clicks will take ~4 seconds to complete.

This is intentional in the design of useActionState.

We have to wait for the previous result of addToCartAction in order to pass the prevCount to the next call to addToCartAction. That means React has to wait for the previous Action to finish before calling the next Action.

You can typically solve this by using with useOptimistic but for more complex cases you may want to consider cancelling queued actions or not using useActionState.


Using multiple Action types

To handle multiple types, you can pass an argument to dispatchAction.

By convention, it is common to write it as a switch statement. For each case in the switch, calculate and return some next state. The argument can have any shape, but it is common to pass objects with a type property identifying the action.

```js src/App.js import { useActionState, startTransition } from 'react'; import { addToCart, removeFromCart } from './api'; import Total from './Total';

export default function Checkout() { const [count, dispatchAction, isPending] = useActionState(updateCartAction, 0);

function handleAdd() { startTransition(() => { dispatchAction({ type: 'ADD' }); }); }

function handleRemove() { startTransition(() => { dispatchAction({ type: 'REMOVE' }); }); }

return (

Checkout

Eras Tour Tickets {isPending ? '🌀' : count}

); }

async function updateCartAction(prevCount, actionPayload) { switch (actionPayload.type) { case 'ADD': { return await addToCart(prevCount); } case 'REMOVE': { return await removeFromCart(prevCount); } } return prevCount; }


```js src/Total.js
const formatter = new Intl.NumberFormat('en-US', {
  style: 'currency',
  currency: 'USD',
  minimumFractionDigits: 0,
});

export default function Total({quantity, isPending}) {
  return (
    <div className="row total">
      <span>Total</span>
      {isPending ? '🌀 Updating...' : formatter.format(quantity * 9999)}
    </div>
  );
}

```js src/api.js hidden export async function addToCart(count) { await new Promise(resolve => setTimeout(resolve, 1000)); return count + 1; }

export async function removeFromCart(count) { await new Promise(resolve => setTimeout(resolve, 1000)); return Math.max(0, count - 1); } ```

```css .checkout { display: flex; flex-direction: column; gap: 12px; padding: 16px; border: 1px solid #ccc; border-radius: 8px; font-family: system-ui; }

.checkout h2 { margin: 0 0 8px 0; }

.row { display: flex; justify-content: space-between; align-items: center; }

.stepper { display: flex; align-items: center; gap: 8px; }

.qty { min-width: 20px; text-align: center; }

.buttons { display: flex; flex-direction: column; gap: 2px; }

.buttons button { padding: 0 8px; font-size: 10px; line-height: 1.2; cursor: pointer; }

.pending { width: 20px; text-align: center; }