React.lazy + Suspense or alternative?

721 Views Asked by At

in my app, I have two large components which include a lot of panels, and every panel has a few or more other components. Which takes a long time to render. I guess 1-2sec.

A simple example of how this works. I have 2x tabs, we can call them tab1 and tab2. If I click on tab1 I will render DummyPanels, if I click on tab2 a will render ResponsivePanels. The issue is, rendering of these panels is slow, the app will freeze for 1-2sec.

So I need something If I rendering these components it will set loading and when components are ready, it will render them. Or will render the first 5 panels and rest gradually.

I find React.lazy + Suspense. On load and the first tab swap(tab1/tab2) it works well. It will set loading, and after that will render components. But the thing is it will work only on the first try, if I after start swapping between tabs it stops using lazy load + suspense. And it's just frozen for a second and rerender panels after that.

I guess it's because of caching, the app will download parts. Cache them and stop calling suspense again.

So the question is, is there a way to work around this to force lazy+suspne on every tab swap? Or do you guys know any better solution, please? Something that will always load loading first and components after or it will render first 5 panels, and render slowly rest of them?

Code snippet, where I render suspense + lazy component. There is just "if" statement if tabIndex === 0 or 1. So tab1 is tabIndex = 0, and tab2 is tabIndex = 1

    const SortableDummyPanels = lazy(() =>
  import("../containers/SortableDummyPanels")
);
const SortableResponsivePanels = lazy(() =>
  import("../containers/SortableResponsivePanels")
);
  return (
<div>
  <div>
    {tabIndex === 0 && (
      <Suspense fallback={<div>Loading...</div>}>
        <SortableDummyPanels />
      </Suspense>
    )}
  </div>
  <div>
    {tabIndex === 1 && (
      <Suspense fallback={<div>Loading...</div>}>
        <SortableResponsivePanels />
      </Suspense>
    )}
  </div>
</div>

);

0

There are 0 best solutions below