Lazy load an image and detect when it's is loaded in React.JS


On this blog, we are going to implement a simple yet very important feature when working with images on React.JS

Feb. 29, 2024
Analyze Image in Vue.JS using Azure Computer Vision - dnilvincent.net
Introduction

On the previous post (Lazy load an image and detect when it's is loaded in Vue.JS), I provided a steps how to add a lazy loading of our images on Vue.JS Application. For this blog, we're going to implement the similar approach but with using React.JS.

If we recall, we learned that there are many factors that need to be considered when working with images on our web application. What kind of compressor should we use to reduce the image size? How long is the loading time of each image? Do we display the image from server or from a CDN? What dimensions should we choose? These are some common questions that we can think of when dealing with images. If the way of loading the images is unappealing, it might have an impact on the users who visit your website.

In today's blog, we're going to implement a basic lazy loading that's already part of the HTML and detect if the image is loaded completely using React.JS

1. Use lazy loading of image attribute

All you need is to add `loading="lazy"` on your image tag.

        <img src="/.." loading="lazy">
      

What the loading attribute does is, it gives control over when the browser should start loading the resource. The lazy value is basically when the viewport reach the element, then it will start fetching the image from the source.

Here's the information about the browser supports of this attribute

source: https://caniuse.com

2. Detect if the image is already loaded using React.JS

Basically, you just need to add onLoad="" on your image tag. That's it!

        <img src='fromSomewhere' loading="lazy" onLoad={loadImage} />
      
Here's the basic example where we add conditions that we only want to display an image once it's loaded.
        const [isImageLoaded, setIsImageLoaded] = useState(false);

const loadImage = () => {
  setIsImageLoaded(true);
};

return (
  <div className="App">
    {isImageLoaded ? null : <div>Loading...</div>}
    <img
      onLoad={loadImage}
      src="fromSomewhere"
    />
  </div>
);
      

You might consider loading images less than 1mb, if it's possible, so that you can have good user experience. Also, if you're using CDN, check if they support caching of your content.

Well, That's it! I hope you enjoy this blog. Have a wonderful day!

If you have some questions or comments, please drop it below 👇 :)

Buy Me A Tea