);
}
async function updateCartAction(prevCount, formData) {
const type = formData.get('type');
switch (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;
}
.total {
font-weight: bold;
}
hr {
width: 100%;
border: none;
border-top: 1px solid #ccc;
margin: 4px 0;
}
In this example, when the user clicks the stepper arrows, the button submits the form and useActionState calls updateCartAction with the form data. The example uses useOptimistic to immediately show the new quantity while the server confirms the update.
When used with a Server Function , useActionState allows the server's response to be shown before hydration (when React attaches to server-rendered HTML) completes. You can also use the optional permalink parameter for progressive enhancement (allowing the form to work before JavaScript loads) on pages with dynamic content. This is typically handled by your framework for you.
See the <form> docs for more information on using Actions with forms.
Handling errors
There are two ways to handle errors with useActionState.
For known errors, such as "quantity not available" validation errors from your backend, you can return it as part of your reducerAction state and display it in the UI.
For unknown errors, such as undefined is not a function, you can throw an error. React will cancel all queued Actions and shows the nearest Error Boundary by rethrowing the error from the useActionState hook.
```js src/App.js
import {useActionState, startTransition} from 'react';
import {ErrorBoundary} from 'react-error-boundary';
import {addToCart} from './api';
import Total from './Total';
function Checkout() {
const [state, dispatchAction, isPending] = useActionState(
async (prevState, quantity) => {
const result = await addToCart(prevState.count, quantity);
if (result.error) {
// Return the error from the API as state
return {...prevState, error: Could not add quanitiy ${quantity}: ${result.error}};
}
if (!isPending) {
// Clear the error state for the first dispatch.
return {count: result.count, error: null};
}
// Return the new count, and any errors that happened.
return {count: result.count, error: prevState.error};
},
{
count: 0,
error: null,
}
);
function handleAdd(quantity) {
startTransition(() => {
dispatchAction(quantity);
});
}
return (
Checkout
Eras Tour Tickets
{isPending && '🌀 '}Qty: {state.count}
handleAdd(1)}>Add 1
handleAdd(10)}>Add 10
handleAdd(NaN)}>Add NaN
{state.error &&
{state.error}
}
);
}
export default function App() {
return (
(
Something went wrong
The action could not be completed.
Try again
)}>
);
}
```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>
<span>
{isPending ? '🌀 Updating...' : formatter.format(quantity * 9999)}
</span>
</div>
);
}
```js src/api.js hidden
export async function addToCart(count, quantity) {
await new Promise((resolve) => setTimeout(resolve, 1000));
if (quantity > 5) {
return {error: 'Quantity not available'};
} else if (isNaN(quantity)) {
throw new Error('Quantity must be a number');
}
return {count: count + quantity};
}
```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;
}
.total {
font-weight: bold;
}
hr {
width: 100%;
border: none;
border-top: 1px solid #ccc;
margin: 4px 0;
}
button {
padding: 8px 16px;
cursor: pointer;
}
.buttons {
display: flex;
gap: 8px;
}
.error {
color: red;
font-size: 14px;
}
```json package.json hidden
{
"dependencies": {
"react": "19.0.0",
"react-dom": "19.0.0",
"react-scripts": "^5.0.0",
"react-error-boundary": "4.0.3"
},
"main": "/index.js"
}
In this example, "Add 10" simulates an API that returns a validation error, which `updateCartAction` stores in state and displays inline. "Add NaN" results in an invalid count, so `updateCartAction` throws, which propagates through `useActionState` to the `ErrorBoundary` and shows a reset UI.
---
## Troubleshooting
### My `isPending` flag is not updating
If you're calling `dispatchAction` manually (not through an Action prop), make sure you wrap the call in [`startTransition`](/reference/react/startTransition):
```js
import { useActionState, startTransition } from 'react';
function MyComponent() {
const [state, dispatchAction, isPending] = useActionState(myAction, null);
function handleClick() {
// ✅ Correct: wrap in startTransition
startTransition(() => {
dispatchAction();
});
}
// ...
}
When dispatchAction is passed to an Action prop, React automatically wraps it in a Transition.
When you use useActionState, the reducerAction receives an extra argument as its first argument: the previous or initial state. The submitted form data is therefore its second argument instead of its first.
```js {2,7}
// Without useActionState
function action(formData) {
const name = formData.get('name');
}
// With useActionState
function action(prevState, formData) {
const name = formData.get('name');
}
---
### My actions are being skipped
If you call `dispatchAction` multiple times and some of them don't run, it may be because an earlier `dispatchAction` call threw an error.
When a `reducerAction` throws, React skips all subsequently queued `dispatchAction` calls.
To handle this, catch errors within your `reducerAction` and return an error state instead of throwing:
```js
async function myReducerAction(prevState, data) {
try {
const result = await submitData(data);
return { success: true, data: result };
} catch (error) {
// ✅ Return error state instead of throwing
return { success: false, error: error.message };
}
}
My state doesn't reset
useActionState doesn't provide a built-in reset function. To reset the state, you can design your reducerAction to handle a reset signal:
const initialState = { name: '', error: null };
async function formAction(prevState, payload) {
// Handle reset
if (payload === null) {
return initialState;
}
// Normal action logic
const result = await submitData(payload);
return result;
}
function MyComponent() {
const [state, dispatchAction, isPending] = useActionState(formAction, initialState);
function handleReset() {
startTransition(() => {
dispatchAction(null); // Pass null to trigger reset
});
}
// ...
}
Alternatively, you can add a key prop to the component using useActionState to force it to remount with fresh state, or a <form> action prop, which resets automatically after submission.
I'm getting an error: "An async function with useActionState was called outside of a transition."
A common mistake is to forget to call dispatchAction from inside a Transition:
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). Either call the returned function inside startTransition, or pass it to an action or formAction prop.
This error happens because dispatchAction must run inside a Transition:
function MyComponent() {
const [state, dispatchAction, isPending] = useActionState(myAsyncAction, null);
function handleClick() {
// ❌ Wrong: calling dispatchAction outside a Transition
dispatchAction();
}
// ...
}
To fix, either wrap the call in startTransition :
import { useActionState, startTransition } from 'react';
function MyComponent() {
const [state, dispatchAction, isPending] = useActionState(myAsyncAction, null);
function handleClick() {
// ✅ Correct: wrap in startTransition
startTransition(() => {
dispatchAction();
});
}
// ...
}
Or pass dispatchAction to an Action prop, is call in a Transition:
function MyComponent() {
const [state, dispatchAction, isPending] = useActionState(myAsyncAction, null);
// ✅ Correct: action prop wraps in a Transition for you
return <Button action={dispatchAction}>...</Button>;
}
I'm getting an error: "Cannot update action state while rendering"
You cannot call dispatchAction during render:
Cannot update action state while rendering.
This causes an infinite loop because calling dispatchAction schedules a state update, which triggers a re-render, which calls dispatchAction again.
function MyComponent() {
const [state, dispatchAction, isPending] = useActionState(myAction, null);
// ❌ Wrong: calling dispatchAction during render
dispatchAction();
// ...
}
To fix, only call dispatchAction in response to user events (like form submissions or button clicks).
Sitemap
Overview of all docs pages