React 18 Image Lazy Load and Handle Broken Image Tutorial

Last Updated on by in React JS

Implementing lazy loading in React can significantly enhance the initial load time — Lazy loading in React drastically betters the page load time.

In this post, you will learn how to easily lazy load images in React JS. We will also teach you how to handle image-loading errors in React.

Lazy loading images is a method in web and mobile app development that delay the loading of images on a web page to a specific duration. It’s a method of loading on-screen images when they are really required.

To create a lazy load images component in React, we will learn how to use React useEffect, useCallback, and useState hooks in the functional component.

On the other hand, we will show you how to handle broken images or image load errors in React function component using React hooks.

You will make an imgProfile component. It will take certain props that will lazy load images and, at the same time, display a unique image when the wrong path or broken image url is passed to the imgProfile component.

Build React Application

If you have already prepared the React app, move to subsequent instruction.

However, if you are starting from scratch, open the console screen of the terminal, type and run the following command using npm.

npx create-react-app my-react-app

Now the app installation is done. Simply navigate to the application folder through the command.

cd my-react-app

You are now utterly ready to create the image lazy loading and error handling in React.

Make New Function Component

A component function can be created easily in React to handle any functionality we need.

Make the components/ folder, navigate into the directory then create the ImgProfile.js file.

Here is the code that is the basic building block of a React function component.

import React from 'react'

function Profile() {
  return (
    <div>ImgProfile page</div>
  )
}

export default ImgProfile

Configure Bootstrap in React

You must have basic knowledge of CSS; It allows you to design the UI component and set up the UI layout.

However, we can do it without knowing CSS and install the Bootstrap library with the given command.

npm i bootstrap --legacy-peer-deps

Now you have to move onto App.js file, here you have to import the Bootstrap CSS path.

import "../node_modules/bootstrap/dist/css/bootstrap.min.css";

function App() {
  return <div></div>;
}

export default App;

Handle Image Lazy Load and Image Load Error

We need to place useState, useCallback, and useEffect hooks in the function component.

The profile component will take specific props that allow passing image path, placeholder and broken image in the image component.

Add code within the components/ImgProfile.js file.

import React from "react";

const ImgProfile = ({ path, placeholder, loadError, ...props }) => {
  const [img, initImg] = React.useState(placeholder || path);

  const onLoad = React.useCallback(() => {
    initImg(path);
  }, [path]);

  const onError = React.useCallback(() => {
    initImg(loadError || placeholder);
  }, [loadError, placeholder]);

  React.useEffect(() => {
    const imageObjt = new Image();
    imageObjt.src = path;
    imageObjt.addEventListener("load", onLoad);
    imageObjt.addEventListener("error", onError);
    return () => {
      imageObjt.removeEventListener("load", onLoad);
      imageObjt.removeEventListener("error", onError);
    };
  }, [path, onLoad, onError]);

  return <img {...props} alt={img} src={img} />;
};

export default ImgProfile;

Set Props in ImgProfile Component

The bootstrap module and profile component must be added or imported into the global component.

Next, you have to also import the ImgProfile component. Create the two components for dealing with image lazy loading and broken image.

Here is how you can add the code to the src/App.js file.

import ImgProfile from "./components/ImgProfile";
import "../node_modules/bootstrap/dist/css/bootstrap.min.css";

function App() {
  return (
    <div className="container">
      <h2 className="mb-3">
        React Image Lazy Load and Image Load Error Example
      </h2>
      <div className="row">
        <div className="col-6">
          <ImgProfile
            style={{ width: 340 }}
            path="https://i.postimg.cc/8CVt73NY/wonderlane-N-As0-VQu7s-unsplash.jpg"
            placeholder="https://i.postimg.cc/8CVt73NY/wonderlane-N-As0-VQu7s-unsplash.jpg"
          />
        </div>

        <div className="col-6">
          <ImgProfile
            style={{ width: 340 }}
            path="https://brokenpath.com/broken.jpg"
            placeholder="https://i.postimg.cc/RZvT9tdr/guerrillabuzz-crypto-pr-Wtol-M5hsj14-unsplash.jpg"
            loadError="https://i.postimg.cc/RZvT9tdr/guerrillabuzz-crypto-pr-Wtol-M5hsj14-unsplash.jpg"
          />
        </div>
      </div>
    </div>
  );
}

export default App;

Test React Application

We are going to start the react development server using the npm command.

npm start

Let’s invoke the local server and see how things are working in the browser.

http://localhost:3000

React Image Lazy Load and Handle Broken Image Tutorial

Conclusion

In this tutorial, we went over step-by-step and shared with you how to build a React image lazy loading component using function component and React hooks.

We also explained how to handle broken images or image-loading error in React.

Hopefully, you will now feel light and confident enough to implement these quite significant functionalities in React function component.