Sub topic 1
Async transitions and pending state with useTransition
Prerequisites
This chapter assumes you can already do the following:
- Write React function components and use
useStateanduseEffect. - Read JSX and tell controlled inputs (value held in state) from uncontrolled inputs (value held by the DOM).
- Write
asyncfunctions, useawait, and callfetch. - Describe what happens when an
awaitpauses a function and later resumes it.
You don't need to know anything about forms, useActionState, or Server Functions. Later chapters cover those. This chapter covers the base they all build on: running an async function inside a transition and reading its pending state.
What a transition is
A transition is a way to tell React that a state update is not urgent. React keeps the current UI responsive and lets the less urgent update finish in the background. Before React 19, you used startTransition for slow renders, such as filtering a large list while the user types.
React 19 extends the idea. The function you pass to startTransition can now be async. React tracks the whole async operation as one transition, from the moment you call startTransition until the returned promise settles. While it runs, React reports it as pending.
That change turns transitions into a general tool for mutations, such as saving a name, posting a message, or deleting a row. React calls a function used this way an Action. The next chapter defines Actions in full. Here, we focus on the mechanics.
What useTransition returns
useTransition takes no arguments and returns an array of two items:
const [isPending, startTransition] = useTransition();isPendingis a boolean. It istruefrom the moment you start a transition until all work in that transition has finished.startTransitionis a function. You pass it the function you want React to run as a transition.
There is also a standalone startTransition exported from react. It works the same way but gives you no isPending. Use the hook version whenever you want to show pending UI.
A first async transition
The component below sends a new name to the server. It disables the button while the request is in flight and shows an error if the request fails.
import { useState, useTransition } from "react";
async function updateName(name) {
const response = await fetch("/api/name", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ name }),
});
if (!response.ok) {
return "Could not update the name.";
}
return null;
}
export function UpdateName() {
const [name, setName] = useState("");
const [error, setError] = useState(null);
const [isPending, startTransition] = useTransition();
function handleSubmit() {
startTransition(async () => {
const message = await updateName(name);
if (message) {
setError(message);
return;
}
setError(null);
});
}
return (
<div>
<input value={name} onChange={(e) => setName(e.target.value)} />
<button onClick={handleSubmit} disabled={isPending}>
Update
</button>
{error && <p>{error}</p>}
</div>
);
}Follow what happens when the user clicks button:
handleSubmitcallsstartTransitionwith an async function.- React runs that function right away and sets
isPendingtotrue. The component re-renders and the button becomes disabled. - The function reaches
await updateName(name)and pauses. The network request runs. The page stays interactive, so the user can keep typing in the input. - The request finishes and the function resumes. It calls
setErrorwith either a message ornull. - The async function returns, its promise settles, and React sets
isPendingback tofalse.
The isPending flag spares you from writing a separate loading state. You don't set it to true before the request, and you don't reset it in a finally block. React derives it from the lifetime of the function you passed in.
Why not just use a loading state?
You could write the same behavior with useState for a loading flag. The hand-written version looks like this:
const [loading, setLoading] = useState(false);
async function handleSubmit() {
setLoading(true);
try {
await updateName(name);
} finally {
setLoading(false);
}
}It works, but you must remember the try/finally. If you forget it, a thrown error leaves the button disabled forever. The transition version cannot get stuck this way, because isPending follows the promise, not your cleanup code. Transitions also integrate with other React features: Suspense, error boundaries, and the hooks in later chapters all understand them.
Rules that affect how you write the function
The function runs immediately
React calls the function you pass to startTransition synchronously. It does not wait for a later render. Any code before the first await runs inside the click handler's call stack, the same as ordinary code.
State updates after an await need their own transition
This is the most common mistake with async transitions. React marks state updates as part of the transition only if they happen in the same synchronous run as the startTransition call. After the first await, React no longer knows the function belongs to a transition. A setState call there is treated as an ordinary, urgent update.
To fix it, wrap the update in another startTransition:
function handleSubmit() {
startTransition(async () => {
const message = await updateName(name);
startTransition(() => {
setError(message);
});
});
}For the simple example above, the difference is hard to see, and the unwrapped version still works. It matters when the update after the await triggers expensive rendering or suspends, because an urgent update can then block the UI or show a fallback you didn't intend. The React team describes this as a current limitation of the async context. Treat the nested startTransition as the safe default for any state update that follows an await.
Text inputs should not be driven by a transition
Never update a controlled input's value inside startTransition. The input must reflect each keystroke immediately, and a transition may delay the update. In the example above, onChange calls setName directly, outside any transition. Only the network request and its result go inside.
Pending state covers the whole transition
If you start a second transition while the first is still running, isPending stays true until all of them have finished. React currently batches ongoing transitions together. If you need exact per-request tracking, such as a separate spinner per row, keep that information in your own state or give each row its own component with its own useTransition.
Handling errors
There are two kinds of failure, and they need different handling.
Expected failures are problems you anticipate, such as a rejected name or a 400 response. Handle these by returning a value or setting state, as updateName does by returning a message string. The component stays mounted and shows the message.
Unexpected failures are thrown errors, such as a network failure with no response. If the async function throws and you do not catch it, React rethrows the error during rendering, so the nearest error boundary catches it. If your component has no error boundary above it, the error can unmount the whole tree. For a user-friendly path, either wrap the risky call in try/catch and set an error state, or add an error boundary around the feature.
The updateName function above uses fetch, which only rejects on network failure. It resolves normally on HTTP 400 or 500 responses, which is why the code checks response.ok. Skipping that check is a frequent bug.
Here is a version that handles both kinds:
function handleSubmit() {
startTransition(async () => {
try {
const message = await updateName(name);
startTransition(() => {
setError(message);
});
} catch {
startTransition(() => {
setError("Network problem. Check your connection and try again.");
});
}
});
}Common pitfalls
| Symptom | Likely cause | Fix |
|---|---|---|
| Button never re-enables | The async function never settles, for example a request with no timeout | Add a timeout or an `AbortController` to the request |
| UI flashes a Suspense fallback after the request | A state update after `await` ran as an urgent update | Wrap it in a nested `startTransition` |
| Typed characters lag or disappear | A controlled input's `setState` was placed inside a transition | Update input state outside the transition |
| App crashes on a failed request | The thrown error reached the render phase with no error boundary | Use `try/catch` or add an error boundary |
| Spinner shows for the wrong row | One `isPending` is shared across many items | Give each item its own component and its own `useTransition` |
Where this fits in the larger picture
useTransition is the lowest-level tool in this tutorial. It gives you pending state and a way to run an async function without blocking the UI, but it leaves other jobs to you: reading form values, storing the result, and clearing errors. The upcoming chapters add tools that handle those jobs.
- Passing a function to a form's
actionprop makes React run it as a transition for you and supplies the form's values. useActionStatestores the result of an Action and its pending flag in one hook.useFormStatuslets child components read the pending state of their parent form.useOptimisticshows a temporary value while the transition runs.
When you meet these, remember that each one sits on top of the same mechanism you used here. A function runs inside a transition, and React reports when it finishes.
Exercise
In the code below, the author sees that isPending becomes true, but the "Saved" message appears as an urgent update that sometimes triggers a Suspense fallback. What is the cause, and how do you fix it?
startTransition(async () => {
await saveDraft(text);
setStatus("Saved");
});
Show answer
setStatus("Saved") runs after an await. React no longer treats code after the first await as part of the transition, so the update is urgent. Wrap it in a nested transition: startTransition(() => { setStatus("Saved"); });.
Exercise
A user clicks a "Delete" button, and the request to the server fails with an HTTP 500 response. Your Action calls await fetch(...) and does not check response.ok. What does the user see, and what should the code do instead?
Show answer
fetch resolves normally on a 500 response, so no error is thrown and the Action finishes as if it succeeded. isPending returns to false and the UI shows no error. The code should check response.ok and return an error message or set error state when it is false.
Exercise
You use one useTransition in a list component and pass isPending to every row's Delete button. The user deletes row 2. What happens to the other rows' buttons, and how can you change this?
Show answer
Every row's button is disabled, because isPending belongs to the whole component and is true while any transition from it runs. Move the row into its own component with its own useTransition call, so each row tracks only its own pending state.