Use Lazy Loading in React like a pro!

Use Lazy Loading in React like a pro!

ยท

2 min read

Introduction

Ever wondered how do huge web sites optimize their response time? How they load only what's required and not the whole content?

Well my friends look no more, this guide is for you!

Lazy Loading is an optimization technique for websites or web apps where, instead of loading the entire web page and rendering it to the user in bulk, we just load the required section first and delay the remaining, until it is needed by the user.

How to start ?!

  • Have a loader in your arsenal

Let's implement a Sharinghan Loader component.

NOTE: I will not go in depth of styling , this is just to make you familiar with a loader implementation

  • import()

This is a way of telling react that we are using dynamic imports i.e. code splitting.

Code Splitting basically is a feature supported by bundlers (Webpack, Rollup,etc) which can create multiple bundles that can be dynamically loaded at runtime.

  • React.lazy

React.lazy lets you render a dynamic import as a regular component.

const Component = React.lazy(() => import("./Component"))

When this component is first rendered , it will automatically load Component

React.lazy takes a function that must call a dynamic import(). This must return a Promise which resolves to a module with a default export containing a React component.

  • Suspense

The lazy component should then be rendered inside a Suspense component which is provided by react itself. This allows us to show some fallback content (loader in our case) while we're waiting for the lazy component to load.

import React, { Suspense } from 'react';
import { Loader } from "./Loader"

const Component = React.lazy(() => import('./Component'));

function MyComponent() {
  return (
    <div>
      <Suspense fallback={ <Loader/> }>
        <Component />
      </Suspense>
    </div>
  );
}

Here, fallback props accepts any React elements that you want to render while waiting for the lazy component to load. Wrapping multiple lazy components with Suspense is also allowed.

...
<Suspense fallback = { <Loader /> }>
    <Component1 />
    <Component2 />
</Suspense>

And that's it my friends, after this you will have your Lazy Loading up and running.

Here's some glimpse of my Lazy Loader.

meme_gif

Just Kidding!

Catch you on another blog, thank you for reading!๐Ÿ‘‹

ย