Defer a value with useDeferredValue
Let a React component render with a lagging copy of a fast-changing value, so typing stays smooth while a heavy child catches up.
When you do not control the code that sets state, you cannot wrap the update in a transition. useDeferredValue gives you a copy of a value that lags behind during urgent updates.
import { memo, useDeferredValue, useState } from 'react';
const Results = memo(function Results({ query }) {
const items = Array.from({ length: 5000 }, (_, i) => `${query} result ${i}`);
return <ul>{items.map((item) => <li key={item}>{item}</li>)}</ul>;
});
export function Search() {
const [query, setQuery] = useState('');
const deferredQuery = useDeferredValue(query);
const stale = query !== deferredQuery;
return (
<div>
<input value={query} onChange={(e) => setQuery(e.target.value)} />
<div style={{ opacity: stale ? 0.5 : 1 }}>
<Results query={deferredQuery} />
</div>
</div>
);
}(type "abc") -> the input updates immediately
-> the list dims, then shows "abc result 0 ..." when React catches upOn an urgent update, React first renders with the old deferred value, which is cheap because Results is memoized and its prop is unchanged. It then renders again in the background with the new value, and drops that render if you type again. See useDeferredValue.
It needs the child to be memoized, or the first pass is as slow as before. Use useTransition when you own the setter and want the pending state.