How to use useTransition for non-urgent UI updates
· Category: React
Short answer
useTransition lets you mark a state update as non-urgent so React can prioritize urgent updates like typing or clicking, keeping the interface responsive.
Steps
- Call
useTransition()to get an[isPending, startTransition]tuple. - Wrap the non-urgent state update inside
startTransition(). - Use
isPendingto show a loading indicator while the transition is in progress.
Example
import { useState, useTransition } from 'react';
function TabContainer() {
const [tab, setTab] = useState('home');
const [isPending, startTransition] = useTransition();
const selectTab = (next) => {
startTransition(() => {
setTab(next);
});
};
return (
<>
{isPending && <Spinner />}
<TabButton onClick={() => selectTab('home')}>Home</TabButton>
<TabPanel>{tab}</TabPanel>
</>
);
}
Tips
- Use transitions for heavy UI switches, not for controlled inputs.
- Combine with
useDeferredValueto defer re-rendering of slow components. - Requires React 18+ concurrent features enabled.