Sub topic 8
Keeping the UI stable with transitions
This chapter assumes you can write function components with useState, and that you have used React.lazy and <Suspense> as covered in earlier chapters. You should also know that a lazy component's first render can suspend while its chunk downloads. The examples use React 18 or later.
The problem: fallbacks replace content that is already on screen
When a lazy component suspends, React shows the fallback of the nearest <Suspense> boundary above it. On first load that is what you want. It becomes a problem when the user is already looking at useful content.
Consider a tab bar. The Profile tab is visible, and the user clicks Settings. The Settings chunk has not been downloaded yet. With a plain state update, React renders the new tab, finds that Settings suspends, and swaps the whole boundary's content for the fallback. The user sees the Profile tab vanish, a "Loading..." message flash for a fraction of a second, and then the Settings tab appear. On a fast connection this flicker is worse than a short wait on the old screen.
A transition tells React that an update is not urgent, so React can keep the old UI on screen until the new UI is ready.
What a transition does
A transition marks a state update as low priority. React renders the result of that update in the background. If that render suspends, React does not commit it. It keeps showing the current UI, which stays interactive, and retries when the awaited promise resolves.
React provides two entry points:
useTransition()returns[isPending, startTransition]. Use it inside components when you want to know that a transition is in progress.startTransitioncan be imported directly fromreact. It does the same marking but gives you noisPendingflag. Use it in code outside components, or when you do not need a pending indicator.
You pass a function to startTransition. Any state updates called synchronously inside that function become part of the transition.
import { startTransition } from 'react';
startTransition(() => {
setTab('settings');
});A worked example: tabs that do not flicker
This component lazy-loads two tab panels. Selecting a tab wraps the state change in a transition.
import { lazy, Suspense, useState, useTransition } from 'react';
const Profile = lazy(() => import('./Profile'));
const Settings = lazy(() => import('./Settings'));
export default function Tabs() {
const [tab, setTab] = useState('profile');
const [isPending, startTransition] = useTransition();
function select(next) {
startTransition(() => setTab(next));
}
return (
<div>
<button onClick={() => select('profile')}>Profile</button>
<button onClick={() => select('settings')}>Settings</button>
<div style={{ opacity: isPending ? 0.6 : 1 }}>
<Suspense fallback={<p>Loading...</p>}>
{tab === 'profile' ? <Profile /> : <Settings />}
</Suspense>
</div>
</div>
);
}Here is what happens when the user clicks Settings for the first time:
select('settings')runs andsetTab('settings')is scheduled as a transition.- React starts rendering the tree with
tab === 'settings'in the background.Settingsis lazy and its chunk is not loaded, so it suspends. - Because this is a transition and the boundary already shows revealed content, React does not commit the fallback. The Profile tab stays visible.
isPendingistrueduring this wait, so the wrapper dims to 60% opacity. This is your feedback that something is happening.- When the chunk arrives, React finishes the background render, commits it, and
isPendingreturns tofalse.
On the second click, the chunk is already cached by the module system, so Settings does not suspend and the switch is immediate.
Which updates should be transitions
A transition suits updates where the user would rather wait on the old view than see a loading state. Common cases:
- Switching tabs or panels that contain lazy components.
- Navigating between pages when the route's component is lazy.
- Opening a section that has already been shown once.
Keep urgent updates out of transitions. Text typed into an input, a toggled checkbox, and a hover highlight must respond at once. If a controlled input's setValue is wrapped in a transition, typing will feel laggy and React may show stale values. A common pattern is to update the input state urgently and put only the expensive or suspending follow-up in a transition.
import { useState, startTransition } from 'react';
export default function Search({ onQuery }) {
const [text, setText] = useState('');
function handleChange(event) {
setText(event.target.value); // urgent: the input must stay responsive
startTransition(() => {
onQuery(event.target.value); // non-urgent: may suspend a results list
});
}
return <input value={text} onChange={handleChange} />;
}When the fallback still appears
Transitions do not remove fallbacks in every case. React's rule is that a transition avoids hiding content that is already revealed. It does not prevent a fallback for content that was never shown.
- A boundary that is mounting for the first time. If the transition causes a new
<Suspense>boundary to appear, and something inside it suspends, that boundary shows its own fallback. The old UI is not replaced, but the new region shows a placeholder. - The initial render. There is no previous UI to keep, so the first load always uses the fallback. A transition cannot help here.
- A different boundary than you expected. The old UI is kept only up to the boundary that was already showing content. If a tab change makes a deeply nested lazy component suspend inside a boundary that was already visible, React keeps the old content in that visible boundary. If the tab contains its own new boundary, that boundary's fallback will show.
This makes the combination useful in practice. A common layout is an outer boundary around the whole page that is never replaced after the first load, and inner boundaries around slow regions that show a skeleton when they first appear.
| Situation | Plain update | Inside a transition |
|---|---|---|
| First page load | Fallback | Fallback |
| Visible boundary content swaps for a suspending component | Fallback replaces content | Old content stays, `isPending` is true |
| A new boundary mounts and suspends | Its fallback appears | Its fallback appears |
| The import fails | Error boundary renders | Error boundary renders |
Using isPending well
isPending is true from the moment the transition starts until React commits the result. It is a good place for lightweight feedback that does not change layout:
- Reduce opacity on the old content, as in the example.
- Show a small spinner next to the clicked button.
- Disable the button that started the transition to prevent repeated clicks.
- Add a thin progress bar at the top of the page.
Avoid feedback that shifts the layout, such as inserting a banner above the content. The goal of the transition is stability, and a moving layout works against it.
Do not show feedback immediately if the wait is usually short. A flash of dimming for 50 ms is its own kind of flicker. You can delay it with a CSS transition on opacity that has a short transition-delay, so that fast loads never show the pending style.
Transitions can be interrupted
React treats the work in a transition as interruptible. If the user clicks Settings and then clicks Profile before the Settings chunk arrives, React abandons the pending Settings render and moves to the newest state. The Settings chunk still finishes downloading and stays cached. Nothing is lost, but the visible UI never shows an intermediate state.
This also means the function you pass to startTransition should only set state. Side effects there, such as sending a request, run immediately and are not tied to whether the transition commits. Put effects in event handlers outside the transition callback, or in useEffect.
Another detail concerns asynchronous callbacks. State updates that happen after an await inside a startTransition callback are not automatically marked as transition updates. In React 19 you can pass an async function, and React tracks it as an action. Even there, an update made after an await should be wrapped in its own startTransition. If you are not sure, keep the callback synchronous and let the suspending render handle the waiting.
Transitions and load failures
A transition does not catch errors. If the dynamic import behind a lazy component rejects, for example because the user went offline, the lazy component throws during the background render. React then renders the nearest error boundary, as it would without a transition, and isPending resets. Keep the error boundary outside the <Suspense> boundary, as described in the previous chapter, so that a failed chunk shows a message and does not leave the user on a dimmed screen.
<ErrorBoundary fallback={<p>Could not load this section.</p>}>
<Suspense fallback={<p>Loading...</p>}>
{tab === 'profile' ? <Profile /> : <Settings />}
</Suspense>
</ErrorBoundary>Common mistakes
- Forgetting the transition on navigation. Lazy route components under a single boundary will flash the page fallback on every first visit to a route unless the navigation update is a transition. Check whether your router already wraps navigation in
startTransition. If you write your own state-based navigation, wrap it yourself. - Calling the state setter outside the callback.
setTab(next)followed bystartTransition(() => {})does nothing useful. The setter must run inside the function you pass. - Putting urgent input state in the transition. This makes inputs feel slow, as described above.
- Expecting a transition to help the first render. It cannot. Use a meaningful fallback or preload the component, which a later chapter covers.
- Never reading
isPending. Without feedback, a slow chunk looks like a frozen button. Show some indication.
Summary of the model
- Suspending in a plain update replaces visible content with the nearest fallback.
- Suspending inside a transition keeps the old UI, and
isPendingreports the wait. - Fallbacks still appear for the first render and for boundaries that are newly mounted.
- Transitions are interruptible, only state updates belong in them, and errors still go to error boundaries.
Exercise
A user clicks a "Reports" tab whose panel is lazy-loaded. The Suspense boundary already shows the "Overview" panel. The click handler calls setTab('reports') directly, and the user sees a flash of "Loading...". Rewrite the handler so the Overview panel stays visible during the load, and explain how to give the user feedback that loading is in progress.
Show answer
Wrap the update in a transition: const [isPending, startTransition] = useTransition(); then startTransition(() => setTab('reports'));. React renders the Reports panel in the background, and because the boundary already shows revealed content it keeps the Overview panel instead of committing the fallback. Use isPending for feedback that does not shift the layout, for example dimming the panel with opacity: isPending ? 0.6 : 1, or disabling the button.
Exercise
You wrap a tab change in startTransition. The new tab's content includes its own <Suspense fallback={<Skeleton />}> boundary around a lazy chart. The user still sees the skeleton for the chart. Is this a bug in the transition? Why or why not?
Show answer
No. A transition only avoids hiding content that is already revealed. The chart's boundary is mounting for the first time as part of the new tab, so there is no revealed content to preserve inside it. React commits the new tab and shows that boundary's fallback while the chart chunk loads. The old tab was swapped out only once the new tab's other content was ready.