Lazy load components in react

Viewed 382

I'm working on a legacy react-app, hence lot of pieces cannot be reasoned about but simply accepted.

So, I have a couple of components that load a lot of dependencies and are obviously not important for the first render. Hence, I tried the following:

  const HeavyComp = lazy(() => import("HeavyComponent.jsx");

  function Home() {
    return <div>
      <HeavyComp />
    </div>
  }

As a result of this, HeavyComponent is loaded as part of main bundle and but is only visible after that component is loaded. This helps by breaking scripting time but FCP is still far away.

So, I tried the following:

 

  function Home() {
    const [ heavyComponent. setHeavyComponent ] = useState(null);

    useEffect(() => {
      setHeavyComponent(
        lazy(() => import("HeavyComponent.jsx")
      );
    }, []);



    return <div>
      {
        heavyComponent && <heavyComponent />
      }
    </div>
  }

I thought this'd help but same as before, FCP was still delayed until heavyComponent was downloaded, parsed and rendered. So my only option was to make it async using setTimeout or better requestIdleCallback.

Is this the best solution or is there something better?

1 Answers

Assuming that with FCP you are referring to "first content paint". The best option is to use the Suspense component. With it, you can add a fallback loader component (<Spinner /> in this example).

import { Suspense, lazy } from 'react';

const HeavyComp = lazy(() => import("HeavyComponent.jsx");

function Home() {
    return <div>
      <Suspense fallback={<Spinner />}>
         <HeavyComp />
      </Suspense>
    </div>
}

React concurrent-mode documentation

Related