Sub topic 11
Choosing Between Transitions, Deferred Values and Debouncing
What this chapter assumes
This chapter assumes you have read the earlier chapters on useTransition, startTransition and useDeferredValue. You should be comfortable with useState, props, React.memo and the idea that a state change triggers a re-render of a component and its children. Here you will not learn a new API. You will learn how to pick the right tool when a UI feels slow.
Start with the symptom, not the API
All three techniques are used for the same complaint: "the page lags when I type or click." They fix different causes.
- A transition marks a state update as non-urgent, so React can render it in the background and interrupt it.
- A deferred value gives you a lagging copy of a value, and React updates that copy in the background.
- Debouncing waits until the input has been quiet for a set time before acting on it.
The first two change how React schedules rendering. Debouncing changes how often your code reacts at all. This difference drives most decisions.
Transitions: when you own the state update
Use a transition when you write the setState call that causes the slow render. You wrap that call in startTransition, and the slow update becomes interruptible. Urgent updates, such as another click or a keystroke, can jump ahead of it.
Transitions fit best in these cases:
- Navigation or tab changes, where a click sets the state that selects a slow screen.
- Two pieces of state, where one is urgent (the input's text) and one is expensive (the filter that drives a big list).
- Cases where you want
isPending, so you can dim old content or show a spinner while the transition runs.
import { useState, useTransition } from 'react';
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} />
</>
);
}Read the value from the event before the transition callback. This keeps the closure simple and avoids reading e.target later. The text update is urgent, so the input never stalls. The filter update is a transition, so the list renders as time allows.
Deferred values: when you only receive the value
Use useDeferredValue when the value comes from somewhere you do not control, or when you do not want to touch the code that sets it. Typical sources are props from a parent, a value from a library hook, or a context. You cannot wrap someone else's setState in startTransition, but you can defer what you read.
import { useState, useDeferredValue, memo } from 'react';
const SlowList = memo(function SlowList({ query, items }) {
const visible = items.filter((item) => item.includes(query));
return (
<ul>
{visible.map((item) => (
<li key={item}>{item}</li>
))}
</ul>
);
});
function App({ items }) {
const [query, setQuery] = useState('');
const deferredQuery = useDeferredValue(query);
return (
<>
<input value={query} onChange={(e) => setQuery(e.target.value)} />
<SlowList query={deferredQuery} items={items} />
</>
);
}On each keystroke React first re-renders with the old deferredQuery. Because SlowList is memoized and its props have not changed, React skips it. Then React starts a background render with the new value. If you type again, React abandons that render and starts over with the newest value.
There is no isPending here. If you want a stale indicator, compare the two values: query !== deferredQuery.
Debouncing: when the work is not only rendering
Debouncing delays a reaction until the user pauses. It is the right tool when the cost is outside React's render phase:
- Network requests, one per keystroke.
- Writes to
localStorageor a server. - Analytics events.
- Expensive computations that run in an effect and not during render.
React cannot make a fetch cheaper by rendering it at low priority. A transition does not reduce the number of requests, and neither does a deferred value.
import { useState, useEffect } from 'react';
function useDebouncedValue(value, delay) {
const [debounced, setDebounced] = useState(value);
useEffect(() => {
const id = setTimeout(() => setDebounced(value), delay);
return () => clearTimeout(id);
}, [value, delay]);
return debounced;
}
function RemoteSearch() {
const [text, setText] = useState('');
const query = useDebouncedValue(text, 300);
const [results, setResults] = useState([]);
useEffect(() => {
if (query === '') {
setResults([]);
return;
}
const controller = new AbortController();
fetch(`/api/search?q=${encodeURIComponent(query)}`, {
signal: controller.signal,
})
.then((res) => res.json())
.then(setResults)
.catch((err) => {
if (err.name !== 'AbortError') console.error(err);
});
return () => controller.abort();
}, [query]);
return (
<>
<input value={text} onChange={(e) => setText(e.target.value)} />
<ul>
{results.map((r) => (
<li key={r.id}>{r.title}</li>
))}
</ul>
</>
);
}The cleanup function cancels the pending timer when value changes again. The AbortController cancels an in-flight request when query changes, so an old response cannot overwrite a newer one.
The cost of debouncing is a fixed delay. With a 300 ms delay, the user waits 300 ms even on a fast device, and the UI stays slow on a slow device once the delay passes. Transitions and deferred values have no fixed delay. They adapt to the device, and on a fast machine the update appears almost at once.
Side-by-side comparison
| Question | Transition | Deferred value | Debounce |
|---|---|---|---|
| What does it change? | Priority of a state update | Priority of re-rendering with a value | How often code reacts |
| Do you need access to `setState`? | Yes | No | Usually no |
| Built-in pending flag? | Yes, `isPending` | No, compare values | No, you build it |
| Fixed delay? | No | No | Yes |
| Reduces network requests? | No | No | Yes |
| Needs `memo` to help? | No | Yes, on the slow child | No |
| Works for slow render caused by a prop? | No | Yes | Partly |
A decision flow
Combining the techniques
The three are not exclusive. A search box that filters a large local list and also queries a server can use all of them. Debounce the server request, and use a deferred value for the heavy local rendering of the results.
import { useState, useDeferredValue, memo } from 'react';
const Results = memo(function Results({ rows }) {
return (
<ul>
{rows.map((row) => (
<li key={row.id}>{row.title}</li>
))}
</ul>
);
});
function Panel({ rows }) {
const deferredRows = useDeferredValue(rows);
const isStale = rows !== deferredRows;
return (
<div style={{ opacity: isStale ? 0.6 : 1 }}>
<Results rows={deferredRows} />
</div>
);
}Here rows could be the output of RemoteSearch above. The debounce limits requests, and the deferred value keeps typing smooth when a large response arrives and must be rendered.
Edge cases and failure modes
Transitions cannot drive a controlled input
State that feeds a controlled input's value must update urgently. If you put setText inside startTransition, React may render the input with an old value, and typed characters can appear to jump or be lost. Keep two states, as in the search example, or defer a copy of the value.
A deferred value does nothing without a memoized child
If the child is not memoized, it re-renders with the new query prop during the urgent render, because the parent re-rendered. The slow work then happens in the urgent render, and the deferral gains nothing. Check that the slow component is wrapped in memo and that its other props are stable.
One huge component cannot be interrupted
React can pause between components, but not in the middle of one component's render function. If a single component does 400 ms of work, the browser is blocked while it runs. Split the work into smaller components, reduce the work, or move the computation elsewhere.
Updates after an `await`
In React 19 the function passed to startTransition can be async. State updates made after an await are not part of the transition unless you wrap them in another startTransition. If you forget, those updates run as urgent updates.
Fast machines hide the problem
On a fast development laptop you may see no difference between approaches. Use the browser's CPU throttling in the performance panel, and the React Profiler, to test on realistic hardware before choosing.
Quick rules
- If the slow part is a request, a write or an effect, debounce or throttle it.
- If the slow part is a render and you control the
setStatecall, use a transition. - If the slow part is a render and you receive the value, use
useDeferredValueand memoize the child. - If you need a built-in pending flag, prefer
useTransition. - If you need both fewer requests and smooth rendering, combine debouncing with a transition or a deferred value.
Exercise
A search page types a query into an input and calls setQuery. The query state drives a fetch in an effect, and a 5,000-row table renders the results. Typing lags, and the server logs show one request per keystroke. Which techniques address each problem, and why can't one technique fix both?
Show answer
The extra requests come from the effect, outside React's render phase. Debounce the query (and abort stale requests) to reduce them. A transition or deferred value would not reduce the request count, because React still runs every effect it is asked to run. The typing lag comes from rendering the 5,000-row table. Fix it with a transition around the state that drives the table, or by passing a useDeferredValue copy of the results to a memoized table component. Debouncing alone would delay the lag instead of removing it, and it adds a fixed delay on fast devices.
Exercise
You use useDeferredValue(query) and pass deferredQuery to <Table query={deferredQuery} />, but typing still feels slow. Table is a normal function component, not wrapped in memo. What is going wrong, and what is the fix?
Show answer
Without memo, Table re-renders in the urgent render, because its parent re-rendered, even though its query prop still holds the old deferred value. The slow work therefore happens before the input can update. Wrap Table in React.memo so React can skip it when its props are unchanged, and make sure its other props are stable.
Exercise
A teammate wraps setText(e.target.value) for a controlled input in startTransition to "make it faster". What problem can this cause, and what should they do instead?
Show answer
A controlled input's value must update urgently. If its state update is a transition, React may render the input with an old value, so typed characters can appear to be lost or to jump. They should keep setText as an urgent update and put only the expensive derived state, such as a filter, inside startTransition. They can also use useDeferredValue on the text and give the deferred copy to the slow part of the UI.