Sub topic 4
Marking updates as transitions with startTransition
This chapter assumes you are comfortable with function components, useState, props, and how a state change causes a component and its children to re-render. You should also know that concurrent rendering lets React pause and resume work, and that you opt in with createRoot. Both points were covered earlier in this tutorial. Here we look at the function that tells React which updates may be paused: startTransition.
What startTransition does
startTransition is a function exported from react. You pass it a callback. Any state update scheduled inside that callback is marked as a transition, which is a low-priority update. React renders transition updates in the background, and it can abandon that work if something more urgent arrives.
import { startTransition } from 'react';
startTransition(() => {
setPage('reports');
});Three facts define the behavior:
- The callback runs immediately and synchronously.
startTransitiondoes not delay your code. - Only state updates scheduled during that call are marked as transitions. Other updates in the same event handler stay urgent.
- The update is not postponed by a timer. React starts rendering it right away, but it yields to the browser and to urgent updates while it works.
Updates without the wrapper are urgent. Urgent updates are the ones the user expects to see immediately, such as typing in a field or pressing a button.
A first example
The following program is complete. The Posts tab renders 200 components that each take about 1 ms, so a plain update would freeze the page for roughly 200 ms.
import { useState, startTransition } from 'react';
import { createRoot } from 'react-dom/client';
function SlowItem({ text }) {
const start = performance.now();
while (performance.now() - start < 1) {
// Simulates 1 ms of expensive rendering work.
}
return <li>{text}</li>;
}
function Posts() {
const items = [];
for (let i = 0; i < 200; i++) {
items.push(<SlowItem key={i} text={`Post ${i}`} />);
}
return <ul>{items}</ul>;
}
function App() {
const [tab, setTab] = useState('about');
function select(nextTab) {
startTransition(() => {
setTab(nextTab);
});
}
return (
<div>
<button onClick={() => select('about')}>About</button>
<button onClick={() => select('posts')}>Posts</button>
{tab === 'about' ? <p>About this site</p> : <Posts />}
</div>
);
}
createRoot(document.getElementById('root')).render(<App />);Click Posts, then click About before the list appears. With the transition, the second click is handled at once. React throws away the half-finished Posts render and shows About. Without startTransition, the page would stay blocked until all 200 items finished rendering, and your second click would wait in the queue.
What happens inside React
The diagram shows how React treats the two kinds of updates.
Two details matter here. First, the old UI stays on screen while the background render runs. The user sees the previous tab, not a blank or partial one. Second, nothing from the interrupted render reaches the screen, so there are no half-updated views.
Transitions replace each other
If you start several transitions in a row, React works on the latest state. Suppose a user clicks Posts, then Contacts, then About quickly. React does not render all three screens in order. It only needs the result of the last update, so the earlier transition renders are dropped.
This is why transitions suit navigation and filtering, where only the final state matters. It is also why you should not use them for updates where each step must be seen, such as a counter that must show every intermediate value.
startTransition versus useTransition
React provides two entry points that mark updates as transitions.
| Feature | `startTransition` (import from `react`) | `useTransition` hook |
|---|---|---|
| Where it can be called | Anywhere, including outside components | Only at the top level of a component or custom hook |
| Pending flag | None | Returns `isPending` |
| Typical use | Libraries, routers, stores, module-level helpers | UI that needs a loading or dimmed state |
| Marks updates as transitions | Yes | Yes |
Use the standalone function when you have no component to hold a hook, or when you do not need a pending indicator. For example, a small helper can live in its own module:
import { startTransition } from 'react';
export function navigate(setPage, nextPage) {
startTransition(() => {
setPage(nextPage);
});
}The next chapter covers useTransition and isPending in detail. When you want the user to know that work is in progress, switch to the hook.
Keeping urgent and non-urgent updates apart
A single event often causes two kinds of updates. Put only the slow, non-urgent one inside the callback.
import { useState, startTransition } from 'react';
function Filter({ items }) {
const [text, setText] = useState('');
const [filter, setFilter] = useState('');
function handleChange(e) {
const value = e.target.value;
setText(value);
startTransition(() => {
setFilter(value);
});
}
const visible = items.filter((item) => item.includes(filter));
return (
<>
<input value={text} onChange={handleChange} />
<ul>
{visible.map((item) => (
<li key={item}>{item}</li>
))}
</ul>
</>
);
}The input shows the new character on the next frame, because setText is urgent. The list catches up when React finishes the background render. Notice that the code reads e.target.value into a local variable first. That keeps the callback independent of the event object.
Transitions and Suspense
A transition interacts with Suspense in a helpful way. If the new screen suspends, for example because it waits for data, React keeps the already visible UI on screen and does not replace it with a Suspense fallback. React shows the fallback only for content that is not yet visible. The old screen stays in place until the new one is ready.
For this to work, the suspending component must use a Suspense-enabled data source, such as a framework's data layer or the use API with a cached promise. The update that triggers the suspense must also be inside the transition. A later chapter treats this combination in full.
Limitations and common pitfalls
You cannot control a text input with a transition
An input's value must update synchronously. If you move the input's own state update into a transition, the field can lag, drop characters, or show stale text.
// Wrong: the input's own state is a transition.
function handleChange(e) {
startTransition(() => {
setText(e.target.value);
});
}Keep one state variable urgent for the input, and a second one for the expensive consumer, as in the Filter example above. If you cannot split the state, useDeferredValue, introduced later, is the alternative.
Updates after an await are not marked
React marks updates that run while the callback executes. In React 18, the callback must be synchronous, and an update that runs later, such as after an await or inside setTimeout, is a normal urgent update.
// Wrong in React 18: setData runs after the callback has returned.
startTransition(async () => {
const data = await fetchData();
setData(data);
});Do the async work outside, then start the transition when the result is ready:
async function load() {
const data = await fetchData();
startTransition(() => {
setData(data);
});
}React 19 accepts async functions in startTransition, but updates after an await still need their own startTransition wrapper. Async transitions get their own chapter.
The callback should only set state
Do not return a value you expect React to use, and do not put side effects such as network calls or logging inside the callback for the sake of timing. startTransition is about scheduling state updates, not about delaying arbitrary code. Code in the callback still blocks the thread while it runs.
A transition does not make a slow component fast
The total rendering work is unchanged. If a single component takes 400 ms to render, React cannot interrupt it midway, because interruption happens between components. The page will still freeze for that 400 ms. A transition helps most when the cost is spread over many components. Splitting a huge component, virtualizing long lists, or reducing the work per render still matters.
Transitions need the concurrent root
The behavior in this chapter depends on rendering with createRoot. If an application still uses the legacy ReactDOM.render, startTransition runs but does not give you interruptible rendering.
Do not wrap everything
Wrapping an update in a transition makes it low priority. A user action that should feel instant, such as toggling a menu, should not be a transition. Use transitions for updates that cause a lot of rendering and where a slightly later result is acceptable.
Summary of the working model
startTransition(callback)runs the callback now and marks the state updates inside it as non-urgent.- React renders those updates in the background, keeps the old UI visible, and discards unfinished work if an urgent update arrives.
- Only the newest transition state matters, so earlier ones can be skipped.
- It has no pending flag. Use
useTransitionwhen you need one. - Updates after an
await, controlled input values, and single huge components are the main cases where it does not help.
Exercise
A search page has const [text, setText] = useState('') for an input and a slow results list that reads text. A teammate wraps setText(e.target.value) in startTransition to make the list faster, and typing now stutters. Explain why, and show how to restructure the handler.
Show answer
The input's value is controlled by text. By making that update a transition, the input becomes low priority and can render late or show stale text. The fix is to split the state: keep text urgent for the input, add a second state such as filter that the list reads, and update it inside the transition. The handler becomes setText(value); startTransition(() => { setFilter(value); });.
Exercise
What is wrong with this React 18 code, and how do you fix it? startTransition(async () => { const user = await fetchUser(id); setUser(user); });
Show answer
The callback is async, and setUser runs after the await, when the callback has already returned. In React 18 that update is not marked as a transition, so it is urgent. Fix it by awaiting outside the transition: const user = await fetchUser(id); startTransition(() => { setUser(user); });. In React 19 an async callback is allowed, but the update after the await still needs its own startTransition.
Exercise
You are writing a router library that updates a page state setter from a plain JavaScript module, and you do not need a loading indicator. Which API do you use, and why?
Show answer
Use the standalone startTransition imported from react. It can be called outside components, while useTransition is a hook that works only at the top level of a component or custom hook. The cost is that it gives you no isPending flag.