Sub topic 10
Dispatching from event handlers with startTransition
Earlier chapters connected useActionState to a form through the action prop. This chapter covers the other way to run the same action: calling the returned dispatcher yourself from a click handler, an effect, or any other code. It assumes you know useState, event handlers, and the signature useActionState(action, initialState) that returns [state, dispatch, isPending].
Why the form is special
When you pass formAction to <form action={...}>, React does three things for you. It collects the fields into a FormData object, resets the uncontrolled fields after the action finishes, and runs the call inside a transition. A transition is React's way of marking an update as non-urgent so it can track it as pending.
An onClick handler gets none of this. The dispatcher is an ordinary function, and nothing wraps it in a transition. If you call it directly, React logs a warning like this:
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` prop or `formAction` prop.The action still runs, but isPending does not update correctly. The fix is to wrap the call in startTransition.
The basic pattern
startTransition is exported from react. You pass it a function, and any action dispatched inside that function counts as part of the transition.
import { startTransition, useActionState } from "react";
async function increment(prevCount, amount) {
await new Promise((resolve) => setTimeout(resolve, 300));
return prevCount + amount;
}
export function Counter() {
const [count, dispatch, isPending] = useActionState(increment, 0);
return (
<button
disabled={isPending}
onClick={() => startTransition(() => dispatch(1))}
>
{isPending ? "Working..." : `Count: ${count}`}
</button>
);
}Three points about this code:
- The action signature stays
(prevState, payload). Here the payload is the number1instead ofFormData. dispatch(1)returns nothing useful. You get the result by readingcounton a later render, not from a return value.- The
isPendingflag from the hook turns true when the transition starts and false when the action settles and the new state is committed.
The startTransition call must contain the dispatch call synchronously. Calling it after an await in your own handler loses the transition context.
// Wrong: dispatch runs after an await, outside the transition scope.
onClick={async () => {
await somethingElse();
startTransition(() => dispatch(1)); // fine, because the call is inside the callback
}}In that snippet the call is correct because startTransition is invoked after the await and wraps dispatch directly. The real mistake is the reverse: putting dispatch after an await inside the transition callback, or calling dispatch with no wrapper at all. Keep dispatch(...) as a direct, synchronous call inside the callback you give to startTransition.
The payload can be anything
Because you control the call, the second argument of the action can be a number, a string, an object, or a FormData you built yourself. A common choice is an object with a type field, which gives you a reducer-like structure with async support.
import { startTransition, useActionState } from "react";
async function todoAction(prevTodos, command) {
await new Promise((resolve) => setTimeout(resolve, 300));
switch (command.type) {
case "toggle":
return prevTodos.map((todo) =>
todo.id === command.id ? { ...todo, done: !todo.done } : todo
);
case "clearDone":
return prevTodos.filter((todo) => !todo.done);
default:
return prevTodos;
}
}
const initialTodos = [
{ id: 1, title: "Write chapter", done: false },
{ id: 2, title: "Review exercises", done: true },
];
export function TodoList() {
const [todos, dispatch, isPending] = useActionState(todoAction, initialTodos);
return (
<div>
<ul>
{todos.map((todo) => (
<li key={todo.id}>
<button
disabled={isPending}
onClick={() =>
startTransition(() => dispatch({ type: "toggle", id: todo.id }))
}
>
{todo.done ? "[x]" : "[ ]"} {todo.title}
</button>
</li>
))}
</ul>
<button
disabled={isPending}
onClick={() => startTransition(() => dispatch({ type: "clearDone" }))}
>
Clear completed
</button>
</div>
);
}The returned default case matters. An action must always return the next state. If a branch returns nothing, the state becomes undefined, and the next render fails on todos.map.
What happens on a click
Dispatching from effects and other code
The rule is about where the call happens, not about event handlers. Any call to the dispatcher outside a form action needs a transition. This includes useEffect, timers, and subscriptions.
import { startTransition, useActionState, useEffect } from "react";
async function loadProfile(prevProfile, userId) {
const response = await fetch(`/api/users/${encodeURIComponent(userId)}`);
if (!response.ok) return { ...prevProfile, error: "Could not load profile." };
return { data: await response.json(), error: null };
}
export function Profile({ userId }) {
const [profile, load, isPending] = useActionState(loadProfile, {
data: null,
error: null,
});
useEffect(() => {
startTransition(() => load(userId));
}, [userId]);
if (isPending) return <p>Loading...</p>;
if (profile.error) return <p role="alert">{profile.error}</p>;
return <p>{profile.data ? profile.data.name : "No profile"}</p>;
}This works, but treat it with suspicion. Fetching data on mount is usually better handled by use with Suspense, a data library, or your framework's loader. Actions are designed for changes the user triggers, such as mutations. The effect version also has no cancellation, so a fast change of userId queues a second call rather than discarding the first (see the queueing chapter).
Comparing the two ways to call an action
| Row | Form `action` prop | Dispatcher in a handler |
|---|---|---|
| Payload | `FormData` | Any value you choose |
| Transition | Added by React | You add `startTransition` |
| Uncontrolled fields reset | Yes | No, nothing to reset |
| Works without client JavaScript | Possible with server functions | No |
| Typical use | Submitting a form | Buttons, toggles, effects |
The last two rows deserve a note. A handler-based dispatch exists only after JavaScript loads, so it cannot take part in progressive enhancement. If a control is really a form submission, keep it as a form and let action do the work.
Common mistakes
- Calling
dispatchwith no transition. You get the console warning and a staleisPending. Search your handlers for baredispatch(calls. - Using
useTransitionfor the pending flag as well. You can calluseTransitionand use itsstartTransitioninstead of the imported one. ItsisPendingthen covers the whole transition, but the one fromuseActionStatealready tracks this action. Using both usually duplicates state. - Reading the event after the transition starts. React 17 and later no longer pools events, but values like
event.currentTargetarenullonce the handler returns. Read what you need into a variable first, then pass it as the payload. - Mutating the previous state. The action should return a new array or object. Calling
prevTodos.push(...)and returning the same array may skip a re-render. - Expecting a return value from
dispatch. It returnsundefined. Put the result in state and render it. - Putting a submit button's logic in
onClickinside a form. If the button is inside a<form action={formAction}>, clicking it already submits. An extraonClickdispatch would run the action twice.
Summary of the rule
Pass the dispatcher to a form or formAction prop, and React supplies the transition. Call it anywhere else, and you supply it with startTransition(() => dispatch(payload)). The action itself does not change between the two cases. Only the payload and the transition wrapper differ.
Exercise
A teammate writes <button onClick={() => dispatch({ type: "clearDone" })}>Clear</button> for a useActionState dispatcher and reports that the button never shows its pending state and the console shows a warning. What is wrong, and what is the corrected code?
Show answer
The dispatcher is called outside a form action and outside a transition, so React cannot track the call and isPending does not update correctly. Wrap the call: <button onClick={() => startTransition(() => dispatch({ type: "clearDone" }))}>Clear</button>, with startTransition imported from react.
Exercise
Your action is async function reset(prevState, payload) { if (payload.type === "reset") return { count: 0 }; }. After you dispatch { type: "other" }, the component crashes when it reads state.count. Why, and how do you fix it?
Show answer
The action returns nothing for any payload other than "reset", so the next state is undefined and reading state.count throws. Add a fallback that returns the previous state, for example return prevState; at the end of the function.