Sub topic 7
Deferring a value with useDeferredValue
This chapter assumes you are comfortable with function components, useState, and props. It also assumes you know that a state change re-renders a component and, by default, all of its children. You should also know that useTransition marks a state update as non-urgent. Here you will learn the sibling tool useDeferredValue, which defers a value instead of an update.
The problem it solves
Consider a search box that filters a long list. Each keystroke updates query. The update re-renders the input and the list. If rendering the list takes 80 ms, the input feels sluggish, because React cannot paint the new character until the list has finished rendering.
useTransition solves this when you control the setState call. Sometimes you don't. The value may arrive as a prop from a parent, from a library hook, or from a router. In those cases you have no setState to wrap in startTransition. useDeferredValue handles this case. You give it a value and it gives you back a copy that lags behind during urgent updates.
The API
const deferredValue = useDeferredValue(value);valueis what you want to defer. It can be any type, but see the pitfalls below.- The return value is the same as
valueon the first render. - After an update, the return value stays at the old value during the urgent render. React then re-renders in the background with the new value.
A complete example
This example runs as shown. Save it as App.jsx in a project with React 18 or later.
import { useState, useDeferredValue, memo } from 'react';
import { createRoot } from 'react-dom/client';
const ITEMS = Array.from({ length: 5000 }, (_, i) => `item ${i}`);
const SlowList = memo(function SlowList({ query, items }) {
const visible = items.filter((item) => item.includes(query));
return (
<ul>
{visible.map((item) => (
<li key={item}>
<SlowRow text={item} />
</li>
))}
</ul>
);
});
function SlowRow({ text }) {
const start = performance.now();
while (performance.now() - start < 0.2) {
// Busy-wait to simulate an expensive row.
}
return <span>{text}</span>;
}
function App() {
const [query, setQuery] = useState('');
const deferredQuery = useDeferredValue(query);
const isStale = query !== deferredQuery;
return (
<>
<input value={query} onChange={(e) => setQuery(e.target.value)} />
<div style={{ opacity: isStale ? 0.6 : 1 }}>
<SlowList query={deferredQuery} items={ITEMS} />
</div>
</>
);
}
createRoot(document.getElementById('root')).render(<App />);Type quickly into the input. The text appears immediately, and the list dims and then catches up. Without useDeferredValue, each keystroke would wait for the list to finish rendering.
What React does internally
When you type a character, React performs two renders instead of one.
- Urgent render.
queryis"a", butdeferredQueryis still"". The input shows the new text.SlowListreceives the same props as before, somemolets React skip it. This render is fast. - Background render. React starts a second render in which
deferredQueryis"a". This render is a low-priority transition-style render, and it can be interrupted.
If you type another character while the background render is running, React abandons that render. It handles the urgent update first, then starts a new background render with the latest value.
The table shows what each render sees while the user types a, then ab.
| Render | `query` | `deferredQuery` | Priority | Can be interrupted |
|---|---|---|---|---|
| Initial | `""` | `""` | Normal | No |
| Urgent, key `a` | `"a"` | `""` | Urgent | No |
| Background, key `a` | `"a"` | `"a"` | Low | Yes |
| Urgent, key `b` | `"ab"` | `""` | Urgent | No |
| Background, key `b` | `"ab"` | `"ab"` | Low | Yes |
The abandoned background render for "a" never commits. The user sees the list go straight from "" to "ab". This is a useful effect of interruptible rendering. React does not spend time painting results that are already out of date.
Detecting stale content
While the background render is running, the list on screen is out of date. Users should be able to tell. Compare the original value with the deferred one:
const isStale = query !== deferredQuery;Use isStale to dim the old content, show a small spinner, or add a label. useDeferredValue has no isPending flag like useTransition, so this comparison is the standard approach.
Why there is no fixed delay
useDeferredValue does not wait for a number of milliseconds. The background render starts immediately after the urgent render. On a fast device the deferred value may catch up so quickly that you never see the stale state. On a slow device the gap is longer. The lag adapts to the hardware, which is the main advantage over a fixed debounce timer.
Suspense and deferred values
If the background render suspends, for example because a child reads data that hasn't loaded, React does not show the Suspense fallback. The old UI stays on screen with the old deferred value until the new content is ready. This avoids replacing visible content with a spinner. The next chapter section on Suspense covers the details. For now, remember that a deferred render can wait without disturbing what the user sees.
Pitfalls
The child must skip the urgent render
If SlowList is not wrapped in memo, it re-renders during the urgent pass too, because its parent re-rendered. The props are the same, but React still calls the component. You then pay the full cost twice, and the input stays slow. The deferred value only helps when the slow child can bail out when its props haven't changed.
Pass primitives or stable objects
React compares the value with Object.is to decide whether it has changed. If you create a new object during render, every render produces a different object, so React keeps scheduling background renders:
// Problem: a new object on every render.
const deferred = useDeferredValue({ query, sort });
// Better: defer the primitives, or a value created outside render.
const deferredQuery = useDeferredValue(query);
const deferredSort = useDeferredValue(sort);Effects see only the settled value
Effects that depend on deferredQuery run only after the background render commits. They never see the intermediate values that React discarded. This is usually what you want, for example for a network request. It also means the effect runs after React has finished the slow render, not before.
It does not reduce network requests
useDeferredValue controls rendering, not events or I/O. If each deferred value triggers a fetch, you may still send many requests while the user types. A debounce, or a request cancel mechanism, is a separate tool for that problem.
It does not make a slow render fast
The background render still costs the same amount of CPU. Deferring only moves the cost out of the urgent path so the input stays responsive. If the list is so heavy that the interface janks even in the background, reduce the work with virtualization or smaller lists.
The value must come from somewhere reactive
Deferring a constant does nothing. The value has to change over time, such as state, a prop, or a context value.
Transition or deferred value
Both tools produce the same underlying behavior: urgent work first, interruptible work second. The difference is where you apply them.
- Use
useTransitionorstartTransitionwhen you own the code that callssetState. You wrap the update and you get anisPendingflag. - Use
useDeferredValuewhen you receive the value and can't wrap the update, or when you want to defer just one part of the UI that depends on a value.
A later chapter compares these with debouncing in more detail.
Exercises
Exercise
A component renders <Chart data={deferredData} />, where deferredData = useDeferredValue(data). Typing into a nearby input is still slow, and a profile shows Chart rendering on every keystroke with unchanged data. What is the most likely cause, and what is the fix?
Show answer
Chart is not wrapped in memo, so it re-renders in the urgent pass whenever its parent re-renders, even though its props are unchanged. Wrap Chart in React.memo so React can skip it during the urgent render and only render it in the background pass when deferredData changes.
Exercise
You write const deferred = useDeferredValue({ text, page }) inside a component, and the list below it keeps re-rendering in the background even when neither value changed. Why does this happen, and how do you fix it?
Show answer
The object literal is a new object on every render, so Object.is sees a changed value each time and React schedules another background render. Defer the primitive values separately, with useDeferredValue(text) and useDeferredValue(page), or defer an object that is created outside of render.