Sub topic 5
useTransition and the isPending flag
This chapter assumes you know function components, useState, props, and how a state change re-renders a component and its children. You should also have read the earlier chapters in this tutorial on urgent versus non-urgent updates and on createRoot. Your app must render through createRoot for anything here to work.
What useTransition gives you
useTransition is a hook that lets you mark a state update as non-urgent. It takes no arguments and returns an array of two items:
const [isPending, startTransition] = useTransition();isPendingis a boolean. It istruewhile a transition you started is still rendering, andfalseotherwise.startTransitionis a function. You pass it a callback, and every state update scheduled inside that callback becomes a transition update.
React treats a transition update as low priority. If an urgent update arrives while React is rendering the transition, such as a click or a keystroke, React pauses the transition work, handles the urgent update first, and then returns to the transition. The user never waits for the slow render before the page reacts to their input.
startTransition keeps the same identity between renders, so you can leave it out of dependency arrays or include it safely.
A worked example: slow tabs
The component below has three tabs. The Posts tab renders 500 slow items, which simulates an expensive screen. Without a transition, clicking Posts freezes the page for a moment, and the tab buttons do not respond until the render finishes.
import { useState, useTransition } from 'react';
import { createRoot } from 'react-dom/client';
function SlowItem({ text }) {
const start = performance.now();
while (performance.now() - start < 1) {
// Block the thread for 1 ms to simulate expensive rendering.
}
return <li>{text}</li>;
}
function TabContent({ name }) {
if (name !== 'Posts') {
return <p>{name} content</p>;
}
const items = Array.from({ length: 500 }, (_, i) => `Post ${i + 1}`);
return (
<ul>
{items.map((text) => (
<SlowItem key={text} text={text} />
))}
</ul>
);
}
function Tabs({ tabs }) {
const [tab, setTab] = useState(tabs[0]);
const [isPending, startTransition] = useTransition();
function selectTab(nextTab) {
startTransition(() => {
setTab(nextTab);
});
}
return (
<div>
{tabs.map((name) => (
<button key={name} onClick={() => selectTab(name)}>
{name}
</button>
))}
<div style={{ opacity: isPending ? 0.6 : 1 }}>
<TabContent name={tab} />
</div>
</div>
);
}
createRoot(document.getElementById('root')).render(
<Tabs tabs={['About', 'Posts', 'Contact']} />
);Click Posts, then click Contact before the Posts content appears. Two things happen:
- The Contact click is handled right away. React abandons the half-finished Posts render and switches to the new target.
- The old content stays on screen, dimmed to 60% opacity, until the new content is ready.
That second point matters. During a transition, React keeps showing the previous UI instead of a blank or partly rendered one. Your code does not have to track the old state yourself.
What happens inside React
When selectTab runs, React does the following:
- It calls your callback immediately and synchronously.
setTab(nextTab)is recorded as a transition update. - It makes a quick urgent render in which
tabstill holds the old value andisPendingistrue. This render is cheap becauseTabContentreceives the same props as before. - It starts the transition render in the background, with
tabset to the new value. This render can be interrupted. - When the transition render finishes, React commits it. The screen shows the new content and
isPendingbecomesfalsein the same commit.
Reading isPending correctly
isPending is a flag about the transition, not about your data. It turns true as soon as you call startTransition, and it turns false when React commits the result of the transition. If a newer transition replaces an older one, isPending stays true across both and only turns false when the final one commits.
Common ways to use it:
- Dim or fade the stale content, as in the example above.
- Show a small inline indicator, such as a spinner next to the tabs.
- Disable a button so the user cannot trigger the same action twice.
Keep the pending indicator light. The urgent render that flips isPending must itself be fast, or you lose the benefit of the transition.
Splitting one input into two states
A transition does not help if you wrap the wrong update. The classic case is a search box with an expensive result list. You need two pieces of state: one for the text the user sees, and one for the value that drives the slow list.
import { memo, useState, useTransition } from 'react';
const ResultList = memo(function ResultList({ items, filter }) {
const visible = items.filter((item) => item.includes(filter));
return (
<ul>
{visible.map((item) => (
<li key={item}>{item}</li>
))}
</ul>
);
});
function Search({ items }) {
const [text, setText] = useState('');
const [filter, setFilter] = useState('');
const [isPending, startTransition] = useTransition();
function handleChange(e) {
const value = e.target.value;
setText(value);
startTransition(() => {
setFilter(value);
});
}
return (
<>
<input value={text} onChange={handleChange} />
{isPending && <p>Updating...</p>}
<ResultList items={items} filter={filter} />
</>
);
}setText is an urgent update, so the input always shows what the user typed. setFilter is a transition, so the list may lag behind the input by a moment. Note that we read e.target.value into a variable first. That keeps the value in a local constant, which is clearer than reading the event object from inside the callback.
The memo around ResultList is an optimization, not a requirement for the transition to work. It lets React skip re-rendering the list during the urgent render, where filter has not changed yet.
Rules for the callback
The function you pass to startTransition has a few constraints:
- It runs immediately. React does not wait before calling it.
- Only state updates scheduled during the call are marked as transitions. Other work in the callback, such as logging or computing values, runs normally and is not deferred.
- It must update state through
useStateoruseReducersetters. Starting a transition with no state update does nothing. - Updates inside it are not applied to controlled text inputs correctly. A controlled input's value must be set by an urgent update.
There is also a standalone startTransition exported from react. It works the same way for marking updates, but it does not return isPending. Use it when you are outside a component, such as in a data library or a router. Inside a component that needs a pending indicator, use the hook.
Common pitfalls
Transitions do not make rendering faster
A transition changes when and how React renders, not how long your components take. A 500 ms render still takes about 500 ms of work. What changes is that the rest of the page stays responsive while that work happens. If the render is slow because of unneeded work, fix that first with memoization or by reducing the number of rendered elements.
Nothing to interrupt
If the transition render is already fast, you will not notice any difference, and isPending may flicker on and off. Add a transition when you have measured a real delay, not by default.
Updates after an await
In React 18, the callback must be synchronous. A state update after await or inside setTimeout is not part of the transition, because the callback has already returned by then. In React 19, the callback may be async, and isPending stays true until the async function finishes. React 19 still has this limitation: state updates made after an await need their own startTransition wrapper.
import { useState, useTransition } from 'react';
async function updateName(name) {
await new Promise((resolve) => setTimeout(resolve, 800));
return name.trim() === '' ? { error: 'Name is required' } : {};
}
function NameForm() {
const [name, setName] = useState('');
const [error, setError] = useState(null);
const [isPending, startTransition] = useTransition();
function handleSubmit() {
startTransition(async () => {
const result = await updateName(name);
startTransition(() => {
setError(result.error ?? null);
});
});
}
return (
<>
<input value={name} onChange={(e) => setName(e.target.value)} />
<button onClick={handleSubmit} disabled={isPending}>
Save
</button>
{error && <p>{error}</p>}
</>
);
}Here isPending disables the button for the whole async call. The inner startTransition keeps the setError update inside the transition.
Suspense and the old UI
If a transition renders a component that suspends, React does not replace the visible content with a Suspense fallback. It keeps the old UI on screen, and isPending stays true until the new content is ready. A later chapter covers this in detail.
Summary table
| Item | Behavior |
|---|---|
| `isPending` | `true` from the call to `startTransition` until the transition commits |
| Callback timing | Runs immediately, synchronously |
| Priority | Transition updates yield to urgent updates |
| Old UI | Stays visible until the new render is ready |
| Controlled inputs | Must be updated urgently, not in a transition |
Exercise
In the Search example, a teammate changes handleChange so that both setText(value) and setFilter(value) are inside the startTransition callback. What goes wrong, and how do you fix it?
Show answer
The input's value is now a transition update, so React can delay it behind urgent work and the input lags or appears to drop keystrokes. The fix is to call setText(value) outside startTransition, so it is urgent, and keep only setFilter(value) inside the callback.
Exercise
A component calls useTransition, and a click handler wraps setCount(count + 1) in startTransition. The render of the component is fast, around 2 ms. Does the transition improve responsiveness? When is isPending useful?
Show answer
No meaningful improvement, because there is no slow render to interrupt, and isPending may flash on and off. isPending is useful when the transition render is slow enough that the user needs feedback, such as dimming stale content or showing a spinner while the new screen renders.