javascript / intermediate
Snippet
Non-blocking Updates with useTransition
The useTransition hook allows you to mark state updates as transitions. These updates are treated as low priority and won't block the UI, keeping the application responsive even during heavy rendering tasks.
snippet.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
function TabContainer() {const [isPending, startTransition] = useTransition();const [tab, setTab] = useState('about');function selectTab(nextTab) {startTransition(() => {setTab(nextTab);});}return (<><TabButton isActive={tab === 'about'} onClick={() => selectTab('about')}>About</TabButton>{isPending && <p>Loading heavy tab...</p>}{tab === 'about' && <AboutTab />}</>);}
react
Breakdown
1
const [isPending, startTransition] = useTransition();
Initializes the hook; isPending indicates if a transition is currently in progress.
2
startTransition(() => { setTab(nextTab); });
Wraps the state update to signal React that it can be interrupted if a higher priority update occurs.