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
useActionState(reducerAction, initialState, permalink?)
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);
// ...
}
Parameters
reducerAction: The function to be called when the Action is triggered. When called, it receives the previous state (initially theinitialStateyou provided, then its previous return value) as its first argument, followed by theactionPayloadpassed todispatchAction.initialState: The value you want the state to be initially. React ignores this argument afterdispatchActionis 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
reducerActionis 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:
- The current state. During the first render, it will match the
initialStateyou passed. AfterdispatchActionis invoked, it will match the value returned by thereducerAction. - A
dispatchActionfunction that you call inside Actions. - The
isPendingflag that tells you if any dispatched Actions for this Hook are pending.
Caveats
useActionStateis 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
dispatchActionsequentially. Each call toreducerActionreceives the result of the previous call. - The
dispatchActionfunction 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
permalinkoption, ensure the same form component is rendered on the destination page (including the samereducerActionandpermalink) so React knows how to pass the state through. Once the page becomes interactive, this parameter has no effect. - When using Server Functions,
initialStateneeds to be serializable (values like plain objects, arrays, strings, and numbers). - If
dispatchActionthrows 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]
dispatchActionmust 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 theinitialState. After the first call todispatchAction, it's equal to the last state returned. -
optional
actionPayload: The argument passed todispatchAction. It can be a value of any type. Similar touseReducerconventions, it is usually an object with atypeproperty 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
reducerActioncan be sync or async. It can perform sync actions like showing a notification, or async actions like posting updates to a server.reducerActionis not invoked twice in<StrictMode>sincereducerActionis designed to allow side effects.- The return type of
reducerActionmust match the type ofinitialState. If TypeScript infers a mismatch, you may need to explicitly annotate your state type. - If you set state after
awaitin thereducerActionyou currently need to wrap the state update in an additionalstartTransition. See the startTransition docs for more info. - When using Server Functions,
actionPayloadneeds to be serializable (values like plain objects, arrays, strings, and numbers).
[!INFO]
Why is it called
reducerAction?The function passed to
useActionStateis 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,
useActionStateis likeuseReducer, 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 <CodeStep step={1}>current state</CodeStep>, initially set to the initial state you provided.
2. The <CodeStep step={2}>action dispatcher</CodeStep> that lets you trigger `reducerAction`.
3. A <CodeStep step={3}>pending state</CodeStep> that tells you whether the Action is in progress.
To call `addToCartAction`, call the <CodeStep step={2}>action dispatcher</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 (
```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
useActionStatequeuing worksTry clicking "Add Ticket" multiple times. Every time you click, a new
addToCartActionis 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
addToCartActionin order to pass theprevCountto the next call toaddToCartAction. 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
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; }
