Basic useTransition Pattern: Search Input Example
You'll learn how to keep a search input responsive while filtering large datasets using useTransition to defer expensive rendering work.
The Core Problem
When you have a search input that filters a large list (say, 10,000 items), typing in the input can feel sluggish. Each keystroke triggers both the input update and the expensive filter operation, blocking the UI. Users experience laggy typing—a terrible experience.
How useTransition Solves This
useTransition lets you mark the expensive filter update as non-urgent. React prioritizes updating the input field (urgent) first, keeping typing smooth, then handles the filter results (non-urgent) afterward.
Think of it like a restaurant: The waiter immediately acknowledges your order (input updates), then tells the kitchen to prepare it when they have capacity (transition updates). You're not left wondering if they heard you.
The Pattern
const [isPending, startTransition] = useTransition();
const [searchTerm, setSearchTerm] = useState('');
const [filteredResults, setFilteredResults] = useState(largeDataset);
function handleSearch(e) {
const value = e.target.value;
// Update input immediately (urgent)
setSearchTerm(value);
// Defer expensive filtering (non-urgent)
startTransition(() => {
const filtered = largeDataset.filter(item =>
item.name.toLowerCase().includes(value.toLowerCase())
);
setFilteredResults(filtered);
});
}
return (
<>
<input value={searchTerm} onChange={handleSearch} />
{isPending && <span>Updating results...</span>}
<ul>{filteredResults.map(item => <li key={item.id}>{item.name}</li>)}</ul>
</>
);
The input updates instantly on every keystroke. The filtering happens in the background without blocking typing. The isPending flag lets you show subtle loading feedback.
Key Takeaway: Wrap expensive state updates in startTransition() to keep user inputs responsive—the input updates immediately while heavy filtering/rendering work happens as a lower-priority background task.