Sub topic 10
Dispatching from event handlers with startTransition
This chapter assumes you know React function components, useState, and the useActionState signature from earlier chapters. It covers calling the dispatcher from places other than a form.
Why the dispatcher needs a transition
When you pass the dispatcher to a form's action prop, React runs it inside a transition for you. A transition is React's way of marking an update as non-urgent, so the UI stays responsive and the pending flag works.
An onClick handler is not a form action. If you call the dispatcher there directly, React has no transition to attach the action to. Wrap the call in startTransition so React treats it like a form submission.
A counter without a form
The dispatcher accepts any value you give it. It does not have to be FormData. The action receives that value as its second argument.
import { startTransition, useActionState } from "react";
async function increment(prevCount, amount) {
return prevCount + amount;
}
export function Counter() {
const [count, dispatch, isPending] = useActionState(increment, 0);
return (
<button
disabled={isPending}
onClick={() => startTransition(() => dispatch(1))}
>
Count: {count}
</button>
);
}Follow one click through this code:
onClickcallsstartTransition, which runs the callback right away.- The callback calls
dispatch(1). React callsincrement(0, 1). - While the promise is unresolved,
isPendingistrueand the button is disabled. - The returned value,
1, becomes the newcount.
The first argument is always the previous state. Your own value comes second, so the action here is (prevCount, amount), not (amount).
Choosing the argument
Because any value works, you can pass numbers, strings, or objects. Pick the shape that makes the action easy to read.
| Call | Second argument in the action |
|---|---|
| `dispatch(1)` | `1` |
| `dispatch({ type: "reset" })` | `{ type: "reset" }` |
| `dispatch(new FormData(form))` | A `FormData` object |
An object with a type field lets one action handle several operations. This is similar to a reducer, but the action may be async and can call APIs.
Common errors
- Missing
startTransition. React logs a warning that the action was called outside a transition, andisPendingdoes not update as expected. Always wrap calls made from event handlers, effects, or timers. - Passing the event to the action. Writing
onClick={dispatch}hands the click event to your action as the second argument. Use an arrow function and pass exactly what you need. - Forgetting the previous state. If the action is written as
async function increment(amount),amountreceives the previous state. Count the arguments. - Reading
countinside the handler. The value you see is from the last render. Compute the next value in the action fromprevCountinstead.
Exercise
A button uses onClick={() => dispatch(5)} with useActionState(add, 0). React warns about a missing transition. What change fixes it, and what is the signature of add if it should add 5 to the count?
Show answer
Wrap the call: onClick={() => startTransition(() => dispatch(5))}, importing startTransition from "react". The action is async function add(prevCount, amount) { return prevCount + amount; }, because the previous state is the first argument and the dispatched value is the second.
Exercise
Why is onClick={dispatch} a bug, even when the dispatcher is wrapped in a transition elsewhere?
Show answer
React passes the click event to the handler, so the action receives the event object as its second argument instead of the value you intended. Use an arrow function that calls dispatch with an explicit value.