React v19: useTransition hook with <Activity />
Source: Dev.to
Overview
I was experimenting with the useTransition hook (React Docs) and noticed that when a UI component loses focus—e.g., the user navigates away while the component is rendering, calculating, or fetching heavy data—the component’s data is not retained. This is expected behavior, but sometimes we want the data to stay “live” so that it isn’t refetched or recalculated each time the user returns.
One solution is to wrap the content with the “ component, which has a mode prop that can be "visible" or "hidden" (React Docs). The default mode is "visible", which is exactly what we need.
Key Steps
1. Use useTransition
const [isPending, startTransition] = useTransition();
2. Simulate a heavy fetch with a delay
const delay = async (ms) => {
return new Promise((resolve) => setTimeout(resolve, ms));
};
3. Start the transition and fetch data
startTransition(async () => {
if (key === "profile") {
await delay(1100); // Simulated latency
await fetchData(); // Replace with real fetch
}
});
4. Wrap the fetched data with “
<>
<TabPanel value="home">
Tab content for Home
{data}
</TabPanel>
<TabPanel value="contact">
Tab content for Contact
</TabPanel>
</>
{isPending ? "Fetching data..." : ""}
Result
The fetched data remains visible even after the user navigates away (e.g., switches to another tab) and then returns to the Profile tab. The “ wrapper preserves the rendered output while the component is not in focus.
The full source code is available in the repository: .
Gap and Recommendations
- Observation: When the user returns to the Profile tab, the data is still displayed, but
isPendingfires again, indicating thatstartTransition(and consequentlyhandleTabChange) runs once more. - Question: Is there a way to make
useTransitionand “ cooperate so that the transition isn’t re‑triggered on tab re‑entry, or is this the default behavior of React’s DOM handling? - Potential improvement: Future updates could address this gap, perhaps by caching the transition state or by providing a mechanism to skip redundant transitions when the data is already present.