useTransition
- React course
- Expert
- Lesson 14/32
- 4 min
Learn to mark heavy updates as low priority with useTransition.
useTransition
useTransition marks an update as deferred. It returns [isPending, startTransition].
When you write startTransition(() => setTab(1)) React prepares this update in the background. Urgent updates (input) paint immediately; the transition applies when ready.
With isPending you can show a loading indicator during the wait. This makes tab switches smooth.
Transition for tab switch
When a tab changes the content can be heavy. Wrapping it in startTransition updates the tab button immediately and prepares the content in the background.
When the user switches tabs quickly React keeps showing the old render and swaps when the new one is ready. This prevents freezing.
With isPending you can dim the button during the transition.
Practice Write the TabSwitcher component
Write TabSwitcher. Keep tab with useState(0) and get isPending and startTransition from useTransition. Return <button onClick={() => startTransition(() => setTab(1))}>Next</button> and isPending ? <p>Loading</p> : <p>{tab}</p>. Export it.
Starter code
// Write the TabSwitcher component hereSample solution
import { useState, useTransition } from 'react';
function TabSwitcher() {
const [tab, setTab] = useState(0);
const [isPending, startTransition] = useTransition();
return (
<div>
<button onClick={() => startTransition(() => setTab(1))}>Next</button>
{isPending ? <p>Loading</p> : <p>{tab}</p>}
</div>
);
}
export default TabSwitcher;Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Fill in the blank: show pending with isPending
const [isPending, startTransition] = useTransition();
return isPending ? <p>____</p> : <Content />;
const [isPending, startTransition] = useTransition();
return isPending ? <p>Loading</p> : <Content />;
Explanation: A loading text is shown while isPending is true.
2 What does startTransition do?
- Hides a component
- Deletes state
- Marks an update as deferred Correct answer
- Adds CSS
Explanation: startTransition prepares the update in the background.
3 Match useTransition concepts
| Term | Meaning |
|---|---|
startTransition |
Deferred update |
isPending |
Pending state |
urgent update |
Painted now |
tab |
Content switched |