What problem does useTransition solve in a React app?
Short answer
useTransition lets you mark a state update as not urgent, so React can keep the screen responsive to more important things, like typing in a search box, while a slower update, like filtering a huge list, happens in the background without freezing the page.
Advertisement
AModel answer
useTransition lets you mark a state update as not urgent, so React can keep the screen responsive to more important things, like typing in a search box, while a slower update, like filtering a huge list, happens in the background without freezing the page.
function SearchPage() {
const [isPending, startTransition] = useTransition();
const [query, setQuery] = useState('');
const [results, setResults] = useState([]);
function handleChange(e) {
setQuery(e.target.value);
startTransition(() => {
setResults(filterHugeList(e.target.value));
});
}
return <input value={query} onChange={handleChange} />;
}Real-world example
A product search page keeps the typing feeling instant even while filtering thousands of products in the background, using useTransition to mark the filtering update as lower priority.
Likely follow-ups
- What does the isPending value returned by useTransition actually tell you?
- How is useTransition different from just using a plain setTimeout to delay an update?
Related topics