Sub topic 11
How repeated submissions are queued
This chapter assumes you know how useActionState returns [state, dispatch, isPending], and that an action function receives (prevState, payload). It also assumes you know that React runs actions inside transitions. Here you will see what happens when dispatch is called again before the previous call has finished.
The behavior in one sentence
For a single useActionState hook, React runs actions one at a time, in the order they were dispatched. Each action receives the result of the previous action as prevState.
You don't write a lock or a queue. React keeps the queue for you, and the action function stays an ordinary async function that reads prevState and returns the next state.
Why the queue exists
An action is like a reducer that is allowed to be asynchronous. A reducer is only correct if every call sees the result of the one before it. Suppose two actions could run at the same time. Both would receive the same prevState, and the one that finished last would overwrite the other's work. That is a lost update.
Here is a shopping list that adds items through a slow server call. The user submits "milk" and then "eggs" quickly. Without a queue, both actions would start with []. Whichever finished last would win, and the list would hold only one item. With the queue, the "eggs" action does not start until "milk" has produced ["milk"], so it returns ["milk", "eggs"].
What happens step by step
The diagram shows two dispatches. The second arrives while the first is still pending.
Points to notice:
isPendingistruefrom the first dispatch until the whole queue has drained. It does not flicker tofalsebetween actions.prevStateinside an action is the latest result React has computed, not the state from your last render. Between the two dispatches the component may not have re-rendered, so the render-timestatecan be stale.- The payload for each dispatch is captured when
dispatchis called. For a form, that means theFormDatareflects what the user typed at the moment of that submit. - The queue belongs to one hook call. Two separate
useActionStatecalls, in the same component or in different ones, run independently of each other.
Seeing the order in code
This counter has a one-second action. The button is not disabled while pending, so you can click it quickly. It also uses startTransition, because the dispatcher is called outside a form action (see the earlier chapter on dispatching from event handlers).
import { startTransition, useActionState } from "react";
async function slowAdd(prevTotal, amount) {
console.log("start, prevTotal =", prevTotal, "amount =", amount);
await new Promise((resolve) => setTimeout(resolve, 1000));
const next = prevTotal + amount;
console.log("done, next =", next);
return next;
}
export function SlowCounter() {
const [total, dispatch, isPending] = useActionState(slowAdd, 0);
return (
<div>
<button onClick={() => startTransition(() => dispatch(1))}>
Add 1
</button>
<button onClick={() => startTransition(() => dispatch(10))}>
Add 10
</button>
<p>Total: {total}</p>
{isPending && <p>Working...</p>}
</div>
);
}Click "Add 1", then "Add 10", then "Add 1" within a second. The console shows the actions running strictly one after another:
start, prevTotal = 0 amount = 1
done, next = 1
start, prevTotal = 1 amount = 10
done, next = 11
start, prevTotal = 11 amount = 1
done, next = 12Each start line appears only after the previous done line. The total takes about three seconds to finish. The final value is 12 regardless of timing, which is the guarantee the queue gives you.
Don't rely on seeing every intermediate total on screen. Actions in transitions are batched, so React may show only the final value once the queue is empty. Use console.log, or the state returned by each action, for logic. Treat the intermediate renders as an implementation detail.
Forms: queuing happens when the button stays enabled
In the form examples from earlier chapters, the submit button used disabled={isPending}. That prevents a second submit from the button, so the queue rarely has more than one entry. The queue still matters in three situations:
- The user presses Enter in a text field. Disabling the button does not stop implicit submission in every case, so a second submit can still reach the form.
- You chose not to disable the button, because you want fast repeated entries such as adding many items to a list.
- You call
dispatchfrom several event sources, such as buttons, keyboard shortcuts, and timers.
Here is the shopping list again, with the button left enabled on purpose:
import { useActionState } from "react";
async function addItem(prevItems, formData) {
const name = String(formData.get("name") ?? "").trim();
if (!name) return prevItems;
await new Promise((resolve) => setTimeout(resolve, 800));
return [...prevItems, name];
}
export function QueuedShoppingList() {
const [items, formAction, isPending] = useActionState(addItem, []);
return (
<form action={formAction}>
<input name="name" type="text" />
<button type="submit">Add</button>
{isPending && <p>Saving...</p>}
<ul>
{items.map((item, i) => (
<li key={i}>{item}</li>
))}
</ul>
</form>
);
}Type "milk" and press Enter, then type "eggs" and press Enter before the first save finishes. The second action starts after the first ends and receives ["milk"] as prevItems, so the list ends as ["milk", "eggs"]. Because FormData is captured at submit time, "eggs" is not lost when the form resets.
Choosing between queueing and blocking
The queue is a default, and you can choose a different policy for your form.
| Goal | Approach | Trade-off |
|---|---|---|
| Every submission must apply, in order | Leave the button enabled and rely on the queue | Total latency is the sum of all actions. The user waits longer for the last one |
| One submission at a time, ignore extras | Set `disabled={isPending}`, and also guard Enter-key submits if that matters | Fast typists may think a submission was ignored |
| Only the latest submission matters, such as a search | Keep a request counter or use an `AbortController` inside the action | The queue still runs old actions, so they must exit early |
The last row is a real limitation. React does not skip queued actions that have become irrelevant. If the user submits five search terms, all five actions run. An action can return prevState right away when its input is out of date, but you have to write that check yourself.
Errors and the queue
If an action throws or rejects, the error is rethrown during render and goes to the nearest error boundary. Actions queued behind the failing one do not carry on as if nothing happened. In the current implementation, the failure cancels the remaining queue.
For expected failures, such as validation or a rejected request, return an error object as state and don't throw. A returned error is a normal result, and the next queued action receives it as prevState. Reserve throw for failures you want the error boundary to handle.
async function saveNote(prev, formData) {
const text = String(formData.get("text") ?? "").trim();
if (!text) return { ...prev, error: "Note cannot be empty." };
const res = await fetch("/api/notes", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ text }),
});
if (!res.ok) return { ...prev, error: "Could not save the note." };
return { notes: [...prev.notes, text], error: null };
}This action never throws. A failed save leaves notes as it was and sets error. If a second submission was already queued, it runs with that state and can succeed, which clears the error.
Common mistakes
- Reading
statefrom the render inside the action. The action closes over the value from when it was created. Use theprevStateargument, which is always current for the queue. - Assuming parallelism. If you expect five dispatches to take as long as one, you will be surprised. They take about five times as long.
- Mutating
prevState. Return a new object or array, as in[...prevItems, name]. Mutating the previous value can break comparisons and make renders skip. - Expecting a shared queue between hooks. A second
useActionStatehook does not wait for the first. If two actions must be serialized, put them in one hook with one action function and branch on the payload. - Relying on
isPendingbetween actions. It staystruefor the whole queue, so it cannot tell you which submission is running. Put an id in the payload and echo it in the returned state if you need that.
Exercise
A component calls const [total, dispatch, isPending] = useActionState(slowAdd, 0). The user clicks a button that dispatches 5, and 200 ms later clicks again to dispatch 7. Each action takes one second and returns prevTotal + amount. What prevTotal does each action receive, what is the final state, and what is isPending at 1.5 seconds?
Show answer
The first action receives 0 and returns 5. The second action is queued and starts only after the first finishes, so it receives 5 and returns 12. The final state is 12. At 1.5 seconds the second action is still running, so isPending is true. It becomes false only after the queue is empty, at about 2 seconds.
Exercise
You want a search form where only the most recent submission matters, but useActionState runs every queued action. Describe one way to avoid wasted work, and say what the action should return for an outdated submission.
Show answer
Keep a counter, for example in a useRef, and increment it on every submit. Pass the current value in the payload (a hidden input works for a form). When an action starts, compare its id with the latest counter value. If it is older, return prevState right away without making a request. An AbortController stored in a ref can also cancel the in-flight request of the previous action. In both cases the action returns prevState unchanged, so the stale submission has no effect on the result.