useTransition for Search: The Classic Use Case
You'll learn how to keep search inputs lightning-fast even when filtering thousands of items.
The Problem: Typing Feels Sluggish
Imagine typing in a search box that filters a list of 10,000 products. Every keystroke triggers expensive filtering logic that blocks the UI. The input field lags behind your typing, creating a frustrating experience where characters appear slowly or out of order.
The Solution: Separate Urgent from Non-Urgent
With useTransition, you mark the filter update as non-urgent while keeping the input update urgent. React prioritizes your typing (high priority) over the filtering work (low priority), making the input feel instant.
function ProductSearch({ products }) {
const [searchTerm, setSearchTerm] = useState('');
const [filteredTerm, setFilteredTerm] = useState('');
const [isPending, startTransition] = useTransition();
const handleSearch = (e) => {
const value = e.target.value;
// Urgent: update input immediately
setSearchTerm(value);
// Non-urgent: mark filtering as transition
startTransition(() => {
setFilteredTerm(value);
});
};
// Heavy filtering logic
const results = products.filter(product =>
product.name.toLowerCase().includes(filteredTerm.toLowerCase())
);
return (
<div>
<input
value={searchTerm}
onChange={handleSearch}
placeholder="Search products..."
/>
{isPending && <span>Searching...</span>}
<ResultsList products={results} />
</div>
);
}
The input reflects searchTerm instantly. The expensive filter uses filteredTerm, which updates at lower priority. While filtering happens, isPending shows a loading indicator without blocking your typing.
Key Takeaway: useTransition keeps inputs responsive by splitting state updates—one for immediate UI feedback, one for expensive operations that can wait.