Sub topic 6
Showing pending and stale content
A transition or a deferred value lets React keep old content on screen while it renders new content in the background. That is good for responsiveness, but the user now sees content that no longer matches their last action. This chapter covers how to tell the user that this is happening, and how to avoid the mistakes that make the feedback worse than none.
This chapter assumes you can write function components with useState, and that you know useTransition and useDeferredValue at the level of the earlier chapters. You should also know that React 18 or later is rendering your app through createRoot.
Two signals for two mechanisms
React gives you a different signal for each mechanism.
| Mechanism | Signal | Where it comes from |
|---|---|---|
| `useTransition` | `isPending` is `true` while the transition is rendering | The second element of the array that `useTransition` returns |
| `useDeferredValue` | The value is stale when `value !== deferredValue` | A comparison that you write yourself |
The two signals have the same purpose. Each one says: "the screen still shows the result of an earlier state, and a newer render is in progress."
Standalone startTransition, imported from react, has no isPending. If you need a pending indicator, use the hook.
Pending UI with isPending
isPending becomes true as soon as you call startTransition. React keeps the current UI on screen and renders the new state in the background. When that render commits, isPending goes back to false in the same commit.
The example below is complete. TabContent is deliberately slow, so you can see the pending state.
import { useState, useTransition } from 'react';
import { createRoot } from 'react-dom/client';
function SlowItem({ label }) {
const start = performance.now();
while (performance.now() - start < 1) {
// Busy-wait to simulate an expensive render.
}
return <li>{label}</li>;
}
function TabContent({ name }) {
const items = [];
for (let i = 0; i < 400; i++) {
items.push(<SlowItem key={i} label={`${name} item ${i}`} />);
}
return <ul>{items}</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
aria-busy={isPending}
style={{ opacity: isPending ? 0.6 : 1 }}
>
<TabContent name={tab} />
</div>
</div>
);
}
createRoot(document.getElementById('root')).render(
<Tabs tabs={['Posts', 'Comments', 'Archive']} />
);The component renders in two passes after a click:
- React renders
Tabswith the sametabvalue andisPendingset totrue. This render is cheap, becauseTabContentreceives the same props. The old content dims. - In the background, React renders
Tabswith the newtab. When it finishes, it commits the new content andisPendingreturns tofalse.
If you click another tab while the second pass is still running, React throws that render away and starts over with the newest state. You never wait for a render that is already out of date.
Showing stale content with a deferred value
useDeferredValue has no flag, but the stale state is easy to compute. During the urgent render, value is new and deferredValue is still the old one. They are equal again once the background render commits.
import { useState, useDeferredValue, memo } from 'react';
const Results = memo(function Results({ query, items }) {
const visible = items.filter((item) => item.includes(query));
return (
<ul>
{visible.map((item) => (
<li key={item}>{item}</li>
))}
</ul>
);
});
export default function SearchPage({ items }) {
const [query, setQuery] = useState('');
const deferredQuery = useDeferredValue(query);
const isStale = query !== deferredQuery;
return (
<>
<input
value={query}
onChange={(e) => setQuery(e.target.value)}
aria-label="Search"
/>
<p role="status">{isStale ? 'Updating results...' : ''}</p>
<div aria-busy={isStale} style={{ opacity: isStale ? 0.6 : 1 }}>
<Results query={deferredQuery} items={items} />
</div>
</>
);
}Two details are worth noting.
- The
role="status"element is always in the DOM. Screen readers announce changes inside an existing live region more reliably than a region that appears at the same moment as its text. Resultsis wrapped inmemo. Without it,Resultswould re-render on every keystroke with the olddeferredQuery, and the deferral would save nothing.
You can compare with !== only when the value is a primitive, or when you pass the same object to both sides. If query is an object that you rebuild on every render, the comparison is always true, and the UI would look permanently stale. Defer primitives, or objects whose identity changes only when their content changes.
What the user sees over time
The diagram shows the states for one update, using a transition as the example.
Choosing a pending indicator
Dimming is not the only option. The right choice depends on how long the wait is and how much the layout can move.
- Dim the old content. This is the safest default. It causes no layout shift, and it says "this is not current yet."
- Show a small inline note, such as the "Updating results..." text above. Put it where the layout already has room for it.
- Show a progress bar at the top of the page. This works well for navigation, where the whole view is changing.
- Avoid replacing the content with a spinner. That throws away the benefit of a transition. The point of a transition is to keep useful content visible.
Avoiding flicker on fast updates
Many transitions finish in under 100 ms. If you dim the content immediately, the user sees a brief flash on every fast update, which is more distracting than no feedback.
You can delay the indicator with a CSS transition, so a fast update never becomes visible:
import { useState, useTransition } from 'react';
function Panel({ children, isPending }) {
return (
<div
aria-busy={isPending}
style={{
opacity: isPending ? 0.6 : 1,
transition: isPending ? 'opacity 0.2s ease 0.15s' : 'opacity 0s',
}}
>
{children}
</div>
);
}
export default function Counter() {
const [count, setCount] = useState(0);
const [isPending, startTransition] = useTransition();
return (
<>
<button
onClick={() => startTransition(() => setCount((c) => c + 1))}
>
Add
</button>
<Panel isPending={isPending}>
<p>Count: {count}</p>
</Panel>
</>
);
}The third value in opacity 0.2s ease 0.15s is the transition delay. The element starts dimming only after 150 ms of pending time. If the transition finishes first, isPending returns to false before the delay ends, and the content never visibly changes. When the transition ends, the 0s duration snaps the opacity back at once.
Keep the delay short. A long delay leaves the user with a frozen-looking screen.
Pitfalls specific to pending and stale UI
The indicator reflects only the transition you started
isPending is true only for state updates inside the startTransition that belongs to that hook. An urgent setState somewhere else does not set it. If two components each call useTransition, each has its own flag.
No pending state on first render
A transition keeps previously shown content visible. On the very first mount there is no previous content, so there is nothing to mark as stale. useDeferredValue behaves the same way: on mount, deferredValue equals value. If the first render of the slow part is expensive, a transition does not help with it. Use Suspense with a fallback for the initial load instead.
Suspense fallbacks that are already visible
When a transition triggers a component that suspends, React does not replace content that is already visible with a Suspense fallback. It keeps the old content and isPending stays true. A fallback does appear for a Suspense boundary that is newly mounted by the transition. Plan your indicators for both cases.
Dimming with no explanation
A dimmed screen can look like a disabled screen, and users may wait for something that is not happening. Add text, a cursor, or aria-busy semantics when the wait can last more than a second.
Disabling controls
It is tempting to disable the buttons while isPending is true. This usually makes the interface feel worse, because it blocks the very input that transitions exist to protect. A new click safely restarts the render. Disable a control only when a repeated action would cause a real problem, such as submitting a form twice.
Accessibility notes
Visual dimming is invisible to screen reader users. Add two things:
- Set
aria-busyon the region that is updating. It signals that the contents may change. - Announce meaningful changes through an element with
role="status"that stays in the DOM.
Avoid announcing every short transition. A status message that fires on each keystroke is noise, so announce the stale state only when it lasts long enough to matter, for example by using the delayed approach above or by debouncing the message itself.
Exercise
A search box uses useDeferredValue(query) and shows "Updating results..." when query !== deferredQuery. On the first page load, the results are slow to appear and the message never shows. Why, and what should you use for the first load?
Show answer
On mount, deferredValue equals value, so query !== deferredQuery is false and there is no stale state. A deferred value only helps with later updates, because it needs old content to keep showing. For the first load, wrap the slow component in a Suspense boundary with a fallback.
Exercise
You add isPending ? 0.6 : 1 as the opacity for a list, and every fast tab switch (about 30 ms) makes the list flash. Name one change that removes the flash without removing the pending indicator for slow updates.
Show answer
Delay the dimming with a CSS transition, for example transition: isPending ? 'opacity 0.2s ease 0.15s' : 'opacity 0s'. The content starts dimming only after 150 ms, so a 30 ms update finishes first and never visibly changes, while a slow update still dims.