Deferring a value
useTransition wraps an update, so you control where the state is set.
Sometimes you do not. The value arrives as a prop, or a slow child needs to lag
behind while the input stays snappy. That is the job of
useDeferredValue:
const [text, setText] = useState('');
const deferredText = useDeferredValue(text);
useDeferredValue returns a copy of the value that lags behind. React
renders once with the previous deferredText, then starts a background render
with the new one. Because the urgent render finishes first, an input bound to
text stays responsive even when the list built from deferredText is
expensive:
<input value={text} onChange={(event) => setText(event.target.value)} />
<Results query={deferredText} />
The deferred value always catches up. React may render the list twice — once
with the stale value, once with the fresh one — so keep that render cheap and
free of side effects. If you can control the update, useTransition is often
the better fit; reach for useDeferredValue when you have a value rather than a
setter.
Your job is to filter a list by the deferred value.
Challenge
Typing in a search box has to filter a list without making every keystroke wait on
it. Export an App component from App.jsx with a labelled Search input and
a list of the fruits apple, banana, and cherry. Track the input in state,
defer it with useDeferredValue, and render only the fruits that include the
deferred text.
The Test types ban into the input and expects the list to contain banana
alone. The starter renders the full, unfiltered list, so the Test fails.