useActionState·续1

.total { font-weight: bold; }

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


When you click to increase or decrease the quantity, an `"ADD"` or `"REMOVE"` is dispatched. In the `reducerAction`, different APIs are called to update the quantity.

In this example, we use the pending state of the Actions to replace both the quantity and the total. If you want to provide immediate feedback, such as immediately updating the quantity, you can use `useOptimistic`.

> [!INFO]
>
> #### How is `useActionState` different from `useReducer`? 
>
> You might notice this example looks a lot like `useReducer`, but they serve different purposes:
>
> - **Use `useReducer`** to manage state of your UI. The reducer must be pure.
>
> - **Use `useActionState`** to manage state of your Actions. The reducer can perform side effects.
>
> You can think of `useActionState` as `useReducer` for side effects from user Actions. Since it computes the next Action to take based on the previous Action, it has to [order the calls sequentially](/reference/react/useActionState#how-useactionstate-queuing-works). If you want to perform Actions in parallel, use `useState` and `useTransition` directly.
>

---

### Using with `useOptimistic`

You can combine `useActionState` with [`useOptimistic`](/reference/react/useOptimistic) to show immediate UI feedback:

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

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

function handleAdd() {
    startTransition(() => {
      setOptimisticCount(c => c + 1);
      dispatchAction({ type: 'ADD' });
    });
  }

function handleRemove() {
    startTransition(() => {
      setOptimisticCount(c => c - 1);
      dispatchAction({ type: 'REMOVE' });
    });
  }

return (
    <div className="checkout">
      <h2>Checkout</h2>
      <div className="row">
        <span>Eras Tour Tickets</span>
        <span className="stepper">
          <span className="pending">{isPending && '🌀'}</span>
          <span className="qty">{optimisticCount}</span>
          <span className="buttons">
            <button onClick={handleAdd}>▲</button>
            <button onClick={handleRemove}>▼</button>
          </span>
        </span>
      </div>
      <hr />
      <Total quantity={optimisticCount} isPending={isPending}/>
    </div>
  );
}

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> <span>{isPending ? '🌀 Updating...' : formatter.format(quantity * 9999)}</span> </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);
}
.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;
}

setOptimisticCount immediately updates the quantity, and dispatchAction() queues the updateCartAction. A pending indicator appears on both the quantity and total to give the user feedback that their update is still being applied.


Using with Action props

When you pass the dispatchAction function to a component that exposes an Action prop, you don't need to call startTransition or useOptimistic yourself.

This example shows using the increaseAction and decreaseAction props of a QuantityStepper component:

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

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

function addAction() { dispatchAction({type: 'ADD'}); }

function removeAction() { dispatchAction({type: 'REMOVE'}); }

return ( <div className="checkout"> <h2>Checkout</h2> <div className="row"> <span>Eras Tour Tickets</span> <QuantityStepper value={count} increaseAction={addAction} decreaseAction={removeAction} /> </div> <hr /> <Total quantity={count} isPending={isPending} /> </div> ); }

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


```js src/QuantityStepper.js
import { startTransition, useOptimistic } from 'react';

export default function QuantityStepper({value, increaseAction, decreaseAction}) {
  const [optimisticValue, setOptimisticValue] = useOptimistic(value);
  const isPending = value !== optimisticValue;
  function handleIncrease() {
    startTransition(async () => {
      setOptimisticValue(c => c + 1);
      await increaseAction();
    });
  }

function handleDecrease() {
    startTransition(async () => {
      setOptimisticValue(c => Math.max(0, c - 1));
      await decreaseAction();
    });
  }

return (
    &lt;span className="stepper">
      &lt;span className="pending">{isPending && '🌀'}&lt;/span>
      &lt;span className="qty">{optimisticValue}&lt;/span>
      &lt;span className="buttons">
        &lt;button onClick={handleIncrease}>▲&lt;/button>
        &lt;button onClick={handleDecrease}>▼&lt;/button>
      &lt;/span>
    &lt;/span>
  );
}

```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);
}
.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;
}

Since <QuantityStepper> has built-in support for transitions, pending state, and optimistically updating the count, you just need to tell the Action what to change, and how to change it is handled for you.


Cancelling queued Actions

You can use an AbortController to cancel pending Actions:

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

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

async function addAction() { if (abortRef.current) { abortRef.current.abort(); } abortRef.current = new AbortController(); await dispatchAction({ type: 'ADD', signal: abortRef.current.signal }); }

async function removeAction() { if (abortRef.current) { abortRef.current.abort(); } abortRef.current = new AbortController(); await dispatchAction({ type: 'REMOVE', signal: abortRef.current.signal }); }

return ( <div className="checkout"> <h2>Checkout</h2> <div className="row"> <span>Eras Tour Tickets</span> <QuantityStepper value={count} increaseAction={addAction} decreaseAction={removeAction} /> </div> <hr /> <Total quantity={count} isPending={isPending} /> </div> ); }

async function updateCartAction(prevCount, actionPayload) { switch (actionPayload.type) { case 'ADD': { try { return await addToCart(prevCount, { signal: actionPayload.signal }); } catch (e) { return prevCount + 1; } } case 'REMOVE': { try { return await removeFromCart(prevCount, { signal: actionPayload.signal }); } catch (e) { return Math.max(0, prevCount - 1); } } } return prevCount; }


```js src/QuantityStepper.js
import { startTransition, useOptimistic } from 'react';

export default function QuantityStepper({value, increaseAction, decreaseAction}) {
  const [optimisticValue, setOptimisticValue] = useOptimistic(value);
  const isPending = value !== optimisticValue;
  function handleIncrease() {
    startTransition(async () => {
      setOptimisticValue(c => c + 1);
      await increaseAction();
    });
  }

function handleDecrease() {
    startTransition(async () => {
      setOptimisticValue(c => Math.max(0, c - 1));
      await decreaseAction();
    });
  }

return (
          &lt;span className="stepper">
      &lt;span className="pending">{isPending && '🌀'}&lt;/span>
      &lt;span className="qty">{optimisticValue}&lt;/span>
      &lt;span className="buttons">
        &lt;button onClick={handleIncrease}>▲&lt;/button>
        &lt;button onClick={handleDecrease}>▼&lt;/button>
      &lt;/span>
    &lt;/span>
  );
}

```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
class AbortError extends Error {
  name = 'AbortError';
  constructor(message = 'The operation was aborted') {
    super(message);
  }
}

function sleep(ms, signal) {
  if (!signal) return new Promise((resolve) => setTimeout(resolve, ms));
  if (signal.aborted) return Promise.reject(new AbortError());

return new Promise((resolve, reject) => {
    const id = setTimeout(() => {
      signal.removeEventListener('abort', onAbort);
      resolve();
    }, ms);

const onAbort = () => {
      clearTimeout(id);
      reject(new AbortError());
    };

signal.addEventListener('abort', onAbort, { once: true });
  });
}
export async function addToCart(count, opts) {
  await sleep(1000, opts?.signal);
  return count + 1;
}

export async function removeFromCart(count, opts) {
  await sleep(1000, opts?.signal);
  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;
}

.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;
}

Try clicking increase or decrease multiple times, and notice that the total updates within 1 second no matter how many times you click. This works because it uses an AbortController to "complete" the previous Action so the next Action can proceed.

[!WARNING]

Aborting an Action isn't always safe.

For example, if the Action performs a mutation (like writing to a database), aborting the network request doesn't undo the server-side change. This is why useActionState doesn't abort by default. It's only safe when you know the side effect can be safely ignored or retried.