4

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?

3
  • what is FCP? can you clarify that first ? Commented Nov 21, 2021 at 14:24
  • ok, you might be looking for something called Suspense, look for the react concurrent programming, reactjs.org/docs/concurrent-mode-suspense.html Commented Nov 21, 2021 at 14:28
  • This works for components that don't have to be rendered immediately. For example, { isTrue()? <div>True</div>: <Header /> }. In this case Header is not downloaded at all, its only downloaded when needed,. Commented Nov 21, 2021 at 17:42

1 Answer 1

0

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

Sign up to request clarification or add additional context in comments.

1 Comment

This works for components that don't have to be rendered immediately. For example, { isTrue()? <div>True</div>: <Header /> }. In this case Header is not downloaded at all, its only downloaded when needed. If the component is to be rendered immediately your FCP is after header is downloaded and executed.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.