Challenge: Concurrent search
- React course
- Expert
- Lesson 30/32
- 6 min
Write a search that stays fluid with useDeferredValue.
Challenge: Concurrent search
In this challenge you will write a concurrent search box with useTransition. The search runs in the background while the input stays smooth.
With isPending a loading indicator is shown during the wait. Results are listed. Even with large lists the app does not freeze. As the user types the results update gradually.
Practice Write the SearchBox component
Write SearchBox. Import useState and useTransition. Keep query with useState(''), get isPending and startTransition from useTransition. Compute items.filter(i => i.includes(query)) as results. Show <input value={query} onChange={e => startTransition(() => setQuery(e.target.value))} /> and isPending ? <p>Searching</p> : <ul>{results.map((r, i) => <li key={i}>{r}</li>)}</ul>. Export it.
Starter code
// Write the SearchBox component hereSample solution
import { useState, useTransition } from 'react';
function SearchBox({ items }) {
const [query, setQuery] = useState('');
const [isPending, startTransition] = useTransition();
const results = items.filter(i => i.includes(query));
return (
<div>
<input value={query} onChange={e => startTransition(() => setQuery(e.target.value))} />
{isPending ? <p>Searching</p> : <ul>{results.map((r, i) => <li key={i}>{r}</li>)}</ul>}
</div>
);
}
export default SearchBox;Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What does useTransition return?
- [state, setState]
- [value, setValue]
- [isPending, startTransition] Correct answer
- [ref, setRef]
Explanation: useTransition returns [isPending, startTransition].
2 Fill in the blank: transition inside input onChange
<input value={query} onChange={e => ____(() => setQuery(e.target.value))} />
<input value={query} onChange={e => startTransition(() => setQuery(e.target.value))} />
Explanation: startTransition defers the update.