Fortune Ikechi Fortune Ikechi is a frontend engineer based in Rivers State, Nigeria. He is a student of the University of Port Harcourt. He is passionate about community and software engineering processes.

The top choices for React lazy loading libraries in 2021

5 min read 1493

React lazy loading libraries in 2021

Lazy loading has become one of the ways to optimize React applications to speed up the load time. It is a method used to prevent loading parts of a webpage that are not viewed or required at the moment. It’s a design method for optimizing web and mobile applications.

The React ecosystem has a number of packages that help to optimize applications through lazy loading. In this post, I’ll highlight some of the top choices for lazy loading React applications.

react-lazyload

react-lazyload is a package for lazy loading React components and images in React applications.

To get started with react-lazyload, we install it by using a packager:

npm i react-lazyload

Now, we can lazy load our components:

import React from "react";
import LazyLoad from "react-lazyload";

export default function App() {
  return (
    <div className="list">
      <LazyLoad height={250} once>
        <img src="https://placedog.net/500/280" alt="dog" />
</LazyLoad>
      <LazyLoad height={250} once>
        <img src="https://placedog.net/500/300" alt="dog" />
      </LazyLoad>
      <LazyLoad height={250} offset={150}>
        <img src="https://placedog.net/500/300" alt="happy dog" />
      </LazyLoad>
    </div>
  );
}

Above, we wrap the LazyLoad component on any element or content we want to lazy load. The height of the element is set using the height attribute. once is a property from react lazyload, meaning once the content is displayed, it won’t be managed by react lazyload.

Some of the pros of react-lazyload include the following:

  • It has only two event listeners for all the lazy-loaded components, therefore, improves performance
  • Has support for one time lazy load and continuous lazy load mode, allowing you to choose a mode depending on a component need
  • It supports decorators
  • It has support for server-side rendering

React-lazyload isn’t the perfect library as it has some cons, one of which is that it can sometimes break your snapshot tests depending on usage in your project and it will add an extra DOM node if added to your project.

You can see the react lazy-load documentation to learn more about react-lazy-load. A CodeSandbox example can be found here.

react-lazy-load-image-component

react-lazy-load-image-component is used to lazy load React components and images, it boasts of support for intersection observer which determines when an element leaves and enters a viewport and it’s also compatible with server-side rendering (SSR).

We made a custom demo for .
No really. Click here to check it out.

To use, first install via npm using the command below:

npm i --save react-lazy-load-image-component

Usage can be seen below:

import React from 'react';
import { LazyLoadImage } from 'react-lazy-load-image-component';

const ReactImage = ({ image }) => (
  <div>
    <LazyLoadImage
      alt={image.alt}
      src={image.src} />
    <span>{image.caption}</span>
  </div>
);

export default ReactImage;

In the above code, we are importing the LazyLoadImage from react-lazy-load-image and wrapping the LazyLoadImage component, other image properties are passed as props.

Some of the pros of react-lazy-load-image-component include:

  • It allows you to specify a custom placeholder for components
  • It allows you to specify events for beforeLoad and afterLoad
  • It is compatible with server-side rendered components and applications
  • It is compatible with TypeScript declarations
  • It comes built-in with visible effects such as blur and opacity transitions
  • It features a customizable threshold

Similar to others, react-lazy-load-image-component has some backsides, some of which are:

  • All images are loaded at once, react-lazy-load-image-component loads all the images that are visible in the viewport, this means if you have a gallery of images then all the images will be loaded on the visible part of your webpage
  • Effects do not work — to make effects work using this package, you’d need to import effect CSS like they did here
  • React setState hook can only work on mounted or mounting components

You can read more about react-lazy-load-image-component on its documentation.

react-lazy-load

react-lazy-load according to its documentation, react-lazy-load is an easy-to-use React component that helps you defer loading content in a predictable way. It features an automatic component inside a scrolling container such as a scrollbar.

react-lazy-load can be used by first installing:

npm install --save react-lazy-load

To load a component using react-lazy-load, you’d wrap the component elements in a LazyLoad component:

import React from 'react';
import LazyLoad from 'react-lazy-load';

const App = () => {
  <div>
    List of cat images
    <div className="filler" />
    <LazyLoad height={500} offsetVertical={200}>
      <img src='http://placekitten.com/200/300' alt='cat' />
    </LazyLoad>    
    <LazyLoad height={500} offsetTop={200}>
      <img src='http://placekitten.com/200/300' alt='cat' />
    </LazyLoad>
    <div className="filler" />
    <LazyLoad height={480} offsetHorizontal={50}>
      <img src='http://placekitten.com/200/300' alt='cat' />
    </LazyLoad>
    <div className="filler" />
    <LazyLoad height={500} offsetTop={200}>
      <img src='http://placekitten.com/200/300' alt='cat' />
    </LazyLoad>
    <div className="filler" />
    <LazyLoad height={480} offsetHorizontal={50}>
      <img src='http://placekitten.com/200/300' alt='cat' />
    </LazyLoad>
    <div className="filler" />

Similar to most lazy loading libraries for React, react-lazy-load uses the LazyLoad component to determine which elements to lazy load.

react-lazy-load has some of the following benefits:

  • It’s fast!
  • Built-in support for IE8+
  • Compared to the others, react-lazy-load has a small bundle size (6kb minified)
  • Built-in support for debounce functions

Some cons of react-lazy-load include the fact that it can sometimes be mistaken for react-lazyload, another is how much it requires you to wrap each optimizable components and elements using LazyLoad.

You can learn more about react-lazy-load here.

gatsby-image

gatsby-image is a speedy image optimization library that was designed to work smoothly with Gatsby GraphQL queries. It features advanced image loading capabilities to help lazy load images for your webpages.

To use gatsby-image, you install:

npm install gatsby-image

gatsby-image depending on the starter file, requires gatsby-transformer-sharp and gatsby-plugin-sharp, they should be installed and added to your gatsby config file:

npm install gatsby-transformer-sharp gatsby-plugin-sharp

Add it to your gatsby config below:

plugins: [`gatsby-transformer-sharp`, `gatsby-plugin-sharp`]

Below is what optimizing a component with gatsby-image looks like:

import React from 'react'
import { graphql } from 'gatsby'
import Img from "gatsby-image"

export default ({ data }) => (
  <div>
    <h1>Hello</h1>
    <Img fixed={data.file.childImageSharp.fixed} />
  </div>
)

export const query = graphql`
  query {
    file(relativePath: { eq: "blog/avatars/kyle-mathews.jpeg" }) {
      childImageSharp {
        fixed(width: 125, height: 125) {
          ...GatsbyImageSharpFixed
        }
      }
    }
  }
`

To accurately define the specification for image processing in queries, we use the childImageSharp property, this is also used to update the UI changes in our webpage. More about gatsby-image can be found here.

Below are some of the benefits of gatsby-image in your React application:

  • It can be optimized for images with fixed height and width
  • It can be optimized for images that stretch beyond containers
  • It automatically adds blue effects and lazy loads images
  • It’s fast!

Although highly optimized, gatsby-images has some cons like it struggles with non-gatsby applications, it can also be difficult for anyone without a basic understanding of graphQL to use.

uselazy

uselazy is a React library for lazy loading and code splitting React components and images. uselazy handles both dynamic and named imports.

uselazy like most of the other libraries can be installed using a package manager:

npm install uselazy

or using yarn:

yarn add uselazy

Usage

/// navbar.jsx

import React from 'react';

const Navbar = () => <p> React is awesome </p>

export default Navbar;


/// Menu.js

import React from 'react';

export const Menu = () = <h2> This is a menu page </h2>


/// App.js

import React, { useState } from 'react';
import useLazy from 'uselazy';

const imports = [() => import('./Navbar'), () => import('./Menu')];

const App = () => {
   const [shouldImport, setShouldImport] = useState(false);
   const { isLoading, result: Components } = useLazy(
      useMemo(() => imports, []),
      shouldImport,
  );

 return (
    <div>
      <h1>I'm very lazy </h1>
      <button onClick={() => setShouldImport(!shouldImport)}>Click menu</button>

      {isLoading && <span>some spinner</span>}

      {Components && Components.map(Component => <Component />)}
    </div>
  );
};

In the above code, uselazy preserves the identity of the imports and adds them as dependencies of useEffect inside uselazy.

Below include some of the benefits of using uselazy in your React application:

  • Built-in support for dynamic and named imports
  • Very small bundle size (31kb)

You can learn more about uselazy here.

Summary

Optimizing React applications by lazy loading components and images for performance is very important in development today. These libraries make it easier than ever to speed up the performance of your React app and improve the overall user experience. Libraries like gatsby-image and react-lazyload are better suited for lazy loading image gallery applications, other libraries like uselazy are better suited for components and React projects with a lot of dynamic and named imports. Libraries like react-lazy-load-image-component with its intersection observer is ideal for TypeScript focused projects due to its very compatible nature with TypeScript but will struggle with performance in a gallery application since it loads all images at the same time.

Full visibility into production React apps

Debugging React applications can be difficult, especially when users experience issues that are hard to reproduce. If you’re interested in monitoring and tracking Redux state, automatically surfacing JavaScript errors, and tracking slow network requests and component load time, try LogRocket.

LogRocket is like a DVR for web apps, recording literally everything that happens on your React app. Instead of guessing why problems happen, you can aggregate and report on what state your application was in when an issue occurred. LogRocket also monitors your app's performance, reporting with metrics like client CPU load, client memory usage, and more.

The LogRocket Redux middleware package adds an extra layer of visibility into your user sessions. LogRocket logs all actions and state from your Redux stores.

Modernize how you debug your React apps — .

Fortune Ikechi Fortune Ikechi is a frontend engineer based in Rivers State, Nigeria. He is a student of the University of Port Harcourt. He is passionate about community and software engineering processes.

One Reply to “The top choices for React lazy loading libraries in…”

Leave a Reply