Use Cases: Lazy Loading with React Suspense

Use Cases: Lazy Loading with React Suspense

Lazy loading is an approach to load incrementally parts ๐Ÿš€ of your app, these could be a route component that is not used often or even a component that depends on heavy dependencies, we'll focus on these 2 use cases.

FYI: there is part of this API that is still experimental, but at least for this use case is good to go.

Contents

  • What is lazy loading?
  • Lazy loading a component relying on many or heavy dependencies
  • Lazy loading routes components

What is lazy loading?

Just to give some context ๐Ÿ˜Ž, sometimes, when you load a page or web app, all the code is bundled in one single js file containing your all custom code. Of course, this is not scalable if you have many components, many dependencies that you don't use at once or are not a high priority to render at first. And also that it adds a waiting time to user before first render is seen, which not a good User Experience...

So lazy loading comes to speed up that initial rendering, by splitting your code into chunks that we can load on demand when the user starts interacting with the app (loaded already the initial scripts, navigated to another route, clicked something, etc)

Lazy loading a component relying on many or heavy dependencies

For this example, we'll imagine that we have a component with a lot of dependencies(like a map or a video player component), I created this sample code, this will be called:

HeavyComponent.tsx

export default function HeavyComponent() {
  return <div>Heavy Component</div>;
}

From app we are going to use this component but... lazy loaded

App.tsx

import { lazy, Suspense } from "react";

import "./styles.css";

// 1)
const LazyHeavyComponent = lazy(() => import("./HeavyComponent"));

const Loading = () => <div>Loading...</div>;

export default function App() {
  return (
    <div className="App">
      Lazy loading example
      {/* 2) */}
      <Suspense fallback={<Loading />}>
        <LazyHeavyComponent />
      </Suspense>
    </div>
  );
}
  1. lazy is responsible for importing the file, and it only supports default exports from the module being lazy imported.
  2. Suspense waits for the component to be loaded and provides a fallback, in this case a loading indication

Lazy loading routes components

Not going to spend much details on routes, because approach is the same, you pass the lazy component instead of the original, to make it load on-demand, when the user navigates there, no matter the router library you use https://reactrouter.com/ or https://reach.tech/router/ .

That's all !!

tenor.gif