Sub topic 11
Keeping Input Responsive with useDeferredValue and useTransition
Prerequisites
This chapter assumes you can read React DevTools Profiler output, you know the difference between a render and a commit, and you have used memo. It also assumes you work in React 18 or later and test timings in a production build. The earlier chapters on unnecessary re-renders and memoization apply here too, because the tools below are a last resort for work that is slow but necessary.
The problem: one render blocks everything
Suppose a search box filters a list of 2,000 rows. Each keystroke calls setQuery, and React must render the input and the list before the browser can paint the typed character. If the list takes 120 ms to render, each keystroke waits 120 ms, and typing feels sticky.
You have already tried the cheaper fixes: state colocation, memo, and virtualization. What remains is a render that is legitimately expensive. Concurrent rendering does not make it cheaper. It changes when the work happens and lets React interrupt it.
Urgent and non-urgent updates
React 18 treats updates as one of two kinds:
- Urgent updates reflect direct interaction, such as typing, clicking, and pressing keys. The user expects an immediate response.
- Transition updates move the UI from one view to another, such as filtered results or a new tab. The user accepts a short delay.
React renders a transition update in the background. While it renders, React checks for new urgent input. If a keystroke arrives, React abandons the in-progress render, handles the keystroke, and restarts the background render with the newest value.
Only the render phase is interruptible. The commit phase, which changes the DOM, always runs to completion. An abandoned render is never committed, so the user never sees a half-finished screen.
useDeferredValue: defer a value you receive
useDeferredValue(value) returns a copy of value that may lag behind. On an update, React first re-renders with the old deferred value, which is fast. It then schedules a second, interruptible render with the new value.
import { memo, useDeferredValue, useState } from "react";
function SlowItem({ name }) {
// Simulates an expensive row by blocking for about 1 ms.
const start = performance.now();
while (performance.now() - start < 1) {}
return <li>{name}</li>;
}
const SlowResults = memo(function SlowResults({ items, query }) {
const visible = items.filter((item) =>
item.name.toLowerCase().includes(query.toLowerCase())
);
return (
<ul>
{visible.map((item) => (
<SlowItem key={item.id} name={item.name} />
))}
</ul>
);
});
const items = Array.from({ length: 1000 }, (_, i) => ({
id: i,
name: `Item ${i}`,
}));
export default function Search() {
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.5 : 1 }}>
<SlowResults items={items} query={deferredQuery} />
</div>
</>
);
}Three details matter here.
SlowResultsis wrapped inmemo. During the first, urgent render,deferredQuerystill has its old value, so the props are unchanged and React skips the list. Withoutmemo, the list re-renders in the urgent pass and nothing improves.query !== deferredQueryis true while the background render is pending. Use it to dim the list so users know it is catching up.- The
itemsarray is defined outside the component. A new array on every render would break thememocomparison.
useDeferredValue is not a debounce. It has no fixed delay, and it starts the background render immediately. On a fast machine the deferred value may follow within the same frame. It also does not reduce total work. It only moves the work out of the way of urgent updates.
In React 19 you can pass an initial value, useDeferredValue(value, ""). On first mount React renders with that initial value, then immediately renders again with the real one.
useTransition: mark a state update as non-urgent
Use useDeferredValue when you receive a value you cannot control, such as a prop. Use useTransition when you own the setState call and can wrap it.
import { useState, useTransition } from "react";
function SlowPosts() {
const rows = [];
for (let i = 0; i < 300; i++) {
const start = performance.now();
while (performance.now() - start < 1) {}
rows.push(<li key={i}>Post {i}</li>);
}
return <ul>{rows}</ul>;
}
export default function Tabs() {
const [tab, setTab] = useState("home");
const [isPending, startTransition] = useTransition();
function select(next) {
startTransition(() => {
setTab(next);
});
}
return (
<>
<button onClick={() => select("home")}>Home</button>
<button onClick={() => select("posts")}>
Posts {isPending && "(loading...)"}
</button>
{tab === "home" ? <p>Welcome</p> : <SlowPosts />}
</>
);
}The hook returns [isPending, startTransition]. isPending is true from the moment the transition starts until its render commits. While the transition renders, the old tab stays on screen and stays clickable. If the user clicks Home again mid-render, React drops the Posts render.
Two rules apply to startTransition:
- The callback must call
setStatesynchronously. AsetStateplaced after anawaitis not marked as a transition unless you wrap it in anotherstartTransition. - The updates it wraps must be state updates. It cannot wrap a controlled text input's
setState, because the input must update urgently. That is the reason for the two-state pattern below.
You can get the same effect as useDeferredValue with two pieces of state:
import { useState, useTransition } from "react";
export function Filter({ items }) {
const [text, setText] = useState("");
const [query, setQuery] = useState("");
const [isPending, startTransition] = useTransition();
function handleChange(e) {
setText(e.target.value); // urgent: keeps the input responsive
startTransition(() => {
setQuery(e.target.value); // non-urgent: drives the slow list
});
}
const visible = items.filter((i) => i.includes(query));
return (
<>
<input value={text} onChange={handleChange} />
{isPending && <span>Updating...</span>}
<ul>{visible.map((i) => <li key={i}>{i}</li>)}</ul>
</>
);
}Choosing between them
| Situation | Use | Why |
|---|---|---|
| You own the `setState` call | `useTransition` | You get `isPending` and can wrap exactly the slow update |
| The value arrives as a prop or from a library hook | `useDeferredValue` | You cannot wrap the setter |
| A single state drives both the input and the slow UI | `useDeferredValue` | Avoids splitting state into two variables |
| Slow work is in the render of many unrelated components | `useTransition` | One wrapper covers every component the update touches |
| The cost is one long synchronous function, not rendering | Neither | Interruption only happens between component renders. Move or chunk the work instead |
What each tool cannot do
- A single component whose render takes 300 ms cannot be interrupted partway. React can only stop between components. If one function blocks for that long, concurrent features will not help, and you need to optimize it or split it.
- Total CPU time stays the same or rises. Interrupted renders are wasted, so on a very slow device you may do more work overall.
- Effects, layout, and the commit still run synchronously after the background render finishes. A slow commit or slow effect will still block input.
- Transitions interact with Suspense. If a transition suspends, React keeps the old UI and sets
isPendinginstead of showing a fallback. This is usually what you want, but it can surprise you if you expected the spinner.
Measuring the effect
Do not trust that the change worked. Verify it with the tools from earlier chapters, in a production build.
- In the React DevTools Profiler, record typing three or four characters before the change. Note the commit duration of each commit.
- Apply the fix and record again. With
useDeferredValueyou should see two commits per keystroke when typing pauses. The first is small (the input) and the second is large (the list). When you type quickly, the large commits are skipped entirely and you see only the final one. - In the browser Performance panel, look at the main thread during typing. Before the fix, each keystroke produces one long task over 50 ms. After the fix, the long tasks are broken into shorter ones, and the input paints between them.
- Check the interaction timings in the Performance panel. Interaction to Next Paint for keystrokes should drop to roughly the cost of rendering the input alone.
If the Profiler shows the list still re-rendering in the first commit, memo is missing or a prop changes identity. Use the "Why did this render?" view to confirm.
Exercise
A teammate wraps setText(e.target.value) for a controlled input in startTransition to fix a slow list. Typing now feels worse, and characters appear late. What went wrong, and what is the fix?
Show answer
The input value is an urgent update, but wrapping it in startTransition lowers its priority, so React may delay it while rendering the slow list. Keep setText outside the transition. Then either wrap a second state update (setQuery) that drives the list in startTransition, or pass the single state through useDeferredValue and wrap the list in memo.
Exercise
You add useDeferredValue(query) but the Profiler still shows the slow list rendering in the same commit as the input, and typing is no faster. Name two likely causes.
Show answer
The list component is not wrapped in memo, so it re-renders whenever its parent does, even when the deferred value has not changed. Or a prop passed to the list changes identity on every render, such as an inline array, object, or function, so memo sees different props. A third possibility is that the slow work is a single long function inside one component, which React cannot interrupt.