DEV Community

Cover image for React v19: useTransition hook with <Activity />
Joma
Joma

Posted on

React v19: useTransition hook with <Activity />

I was playing around with useTransition hook (https://react.dev/reference/react/useTransition) and noticed that it doesn't keep data when a particular UI component loses its focus (e.g. user navigates to somewhere else while component is rendering its content, calculating something or fetching a really heavy data), which is obvious 😉 but what if I want them to keep its data "live" and not to fetch or calculate over and over when user comes back? One of the solutions is using wrapper like this:

 <Activity>
   <div>{data}</div>
  </Activity>
Enter fullscreen mode Exit fullscreen mode

Activity has two props and one of them is mode which can be visible or hidden (https://react.dev/reference/react/Activity).
If omitted, it stays visible by default which is exactly what I wanted!

🗝️Key steps I took:

  • used useTransition hook and called startTransition function (React calls it Action)
 const [isPending, startTransition] = useTransition();
Enter fullscreen mode Exit fullscreen mode
  • created a custom delay function to simulate fetching a heavy data with dummyjson.com API and called it inside startTransition before fetching
const delay = async (ms) => {
    return new Promise((resolve) => setTimeout(resolve,ms));
};


 startTransition(async () => {
   if (key === "profile") {
     await delay(1100);
     await fetchData();
 }
Enter fullscreen mode Exit fullscreen mode
  • *wrapped fetched data with Activity wrapper to keep data visible after particular UI component loses its focus *
 <div>
      <Tabs
        activeKey={defaultTabKey}
        onSelect={handleTabChange}
        defaultActiveKey="home"
        id="uncontrolled-tab-example"
        className="mb-3"
      >
        <Tab eventKey="home" title="Home">
          Tab content for Home
        </Tab>
        <Tab eventKey="profile" title="Profile">
          <Activity>
            <div>{data}</div>
          </Activity>
        </Tab>
        <Tab eventKey="contact" title="Contact">
          Tab content for Contact
        </Tab>
      </Tabs>
       <p>{isPending ? "Fetching data..." : ""}</p>
    </div>
Enter fullscreen mode Exit fullscreen mode

🎯So the result is fetched data that is always present even tough user navigates to somewhere else (in my case when user clicks on another tab inside tab group)


Full code is available at (https://github.com/majalojo/reactv19.git)

Here's the image of the source code:


Main gap and recommendations
We see data is present when user comes back to a profile Tab, but we also see that isPending fired again so that means startTransition and handleChange, too. Is there any solution to make useTransition and Activity cooperate, or is it a default React's DOM behaviour? So this solution should be updated in the future regarding this gap.

Top comments (0)