Intermediate LevelReact JS & React 19
How does useTransition keep the UI responsive during heavy state updates?
❓ Interview Prompt: Explain `useTransition`, `isPending`, marking non-urgent state updates, keeping main thread responsive, and Concurrent React.
'useTransition' is a Concurrent React hook that allows marking specific state updates as non-urgent transitions:
Problem Solved:
Heavy state updates (like filtering a list of 10,000 items) block the main thread, causing user typing input to freeze.
•
Solution: Wrap the heavy state update in 'startTransition(() => setFilter(value))'. React renders urgent typing input immediately, while calculating the heavy list filter in the background!
Code Implementation Example
jsx
import { useState, useTransition } from 'react';
function FilterableList({ items }) {
const [query, setQuery] = useState('');
const [filtered, setFiltered] = useState(items);
const [isPending, startTransition] = useTransition();
const handleSearch = (e) => {
const value = e.target.value;
setQuery(value); // Urgent update: Render input text immediately!
startTransition(() => {
// Non-urgent update: Calculate heavy list filter in background
setFiltered(items.filter(item => item.name.includes(value)));
});
};
return (
<>
<input value={query} onChange={handleSearch} />
{isPending && <p>Filtering list...</p>}
<ItemList items={filtered} />
</>
);
}💡Marking heavy list filtering as non-urgent transitions using useTransition.
🎯 Interview Key Takeaway
Use useTransition to mark heavy re-renders as non-urgent transitions, keeping user input typing smooth and responsive.
#useTransition#Concurrent React#Performance#Intermediate
Back to all React JS & React 19 Questions→