React Lazy Load Image and Handle Image Loading Error Tutorial

React Image Lazy loading example. To enhance user engagement, we must provide a seamless user experience. There are tons of tiny things that can be added or improved to quantify the user experience of websites.

In this profound guide, we will cover how to dynamically lazy load local images in React js application with the help of React Hooks. Not just that, you will also learn how to handle image loading error in React.

We will create an image loading component; this image component will lazy load the images and at the same time efficiently handle the broken images or when the actual image is not available.

Set Up React Project

We need a starting point. To begin creating the functionality, make sure to run command to create a new React app.

If you already have a React app, ignore this step.

npx create-react-app my-react-app

Get inside the project directory.

cd my-react-app

Install Bootstrap Library

Install the bootstrap library to create the UI. Execute command to install the bootstrap library, however, this package is totally optional.

npm install bootstrap

Create Image Component File

Now, you need to make the new functional component, therefore create the features/ImgHandler.js file.

import React from 'react'

function ImgHandler() {
  return (
    <div></div>
  )
}

export default ImgHandler

Create Image Component

Import useEffect, useState, and useCallback hooks. Create the ImgHandler const, pass the properties and props object to build the image component.

Insert the code into the features/ImgHandler.js file.

import React, { useEffect, useState, useCallback } from "react";

const ImgHandler = ({ imgSrc, placeholder, imgErrorHandler, ...props }) => {
  const [image, setImage] = useState(placeholder || imgSrc);

  const onLoad = useCallback(() => {
    setImage(imgSrc);
  }, [imgSrc]);

  const onError = useCallback(() => {
    setImage(imgErrorHandler || placeholder);
  }, [imgErrorHandler, placeholder]);

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

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

export default ImgHandler;

Add Component in App Js

To make the component available in React, make sure to import the ImgHandler component into the src/App.js file.

import "../node_modules/bootstrap/dist/css/bootstrap.min.css";
import "./App.css";
import ImgHandler from "./features/ImgHandler";

function App() {
  return (
    <div className="container mt-5">
      <div className="row">
        <div className="col-6">
          <h2 className="mb-3">React Image Lazy Loading Example</h2>
          <ImgHandler
            style={{ width: 450, height: 400 }}
            placeholder="https://via.placeholder.com/350"
            imgSrc="https://i.postimg.cc/RCG2J693/kenny-eliason-z-FSo6bn-ZJTw-unsplash.jpg"
          />
        </div>

        <div className="col-6">
          <h2 className="mb-3">React Image Loading Error Example</h2>
          <ImgHandler
            imgErrorHandler="https://placehold.jp/e00b72/ffffff/350x350.png?text=No%20Image%20Available"
            placeholder="https://via.placeholder.com/350"
            imgSrc="https://nowhere.com/no-image.jpg"
          />
        </div>
      </div>
    </div>
  );
}

export default App;

Start Development Server

In the final step, you will have to run the command to start the react development server.

npm start

Start the React app on the browser with following URL:

http://localhost:3000

React Lazy Load Image and Handle Image Loading Error Tutorial

Conclusion

Lazy loading is the technique of delaying load or invocation of resources, objects such as text, images, etc. Image lazy loading is a technique that is widely used in modern application development. It defers the loading of images on a web age.

In this guide, we learned two techniques:

How to create an image lazy loading component in React.

How to show an image placeholder when the image loading error occurs in React.