'Best way to lazy load sections in the same page

I have a webpage built with Gatsby, in which the index page contains multiple sections, making it quite long (visually) and heavy (in terms of bundle size). My idea is to code split it.

I'm using React 18, I have to think of two ways of doing code splitting.

  1. Wrap each lazy section in their own Suspense.
const IndexPage = () => (
  <Fragment>
    <main>
      <Suspense>
        <LazySection1 />
      </Suspense>
      <Suspense>
        <LazySection2 />
      </Suspense>
      {/* {...} */}
    </main>
    <Suspense>
      <LazyFooter />
    </Suspense>
  </Fragment>
);
  1. Wrap all lazy sections into one Suspense
const IndexPage = () => (
  <Suspense>
    <main>
      <LazySection1 />
      <LazySection2 />
      {/* {...} */}
    </main>
    <LazyFooter />
  </Suspense>
);

From my understanding, for option (1), the null fallback will be less noticeable, but I lost the new selective hydration. And option (2) is the opposite. The layout shift while reloading the page is massive and ugly. But I can make use of selective hydration and my lighthouse score does get better when using option 2.

Any suggestions on how I should handle this?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source