How Should I Implement Lazy Loading for My Images in React?

I'm trying to add lazy loading to my react application as I have over 200 images that I don't need on the initial load. If I lazy load the images, does this mean, they won't be loaded until they're needed on the screen?

I'm currently importing 4 groups of about 50 images into .js files and then adding them to objects so they can be dynamically used in my components. It looks like this...

// SportImages.js file
import Football from './images/football.png
import Cricket from './images/cricket.png
import Soccer from './images/soccer.png
... // another 50 or so imports

export default {
  Football,
  Cricket,
  Soccer,
  ... // another 50 or so files
}

// and then in my component
cards.map(x => {
  return (
    <img src={SportImages[x.image_ref]} />
  )
})

So my question is, should I be using lazy loading in the component file or in the main images file if I want to lazy load every image?

3

2 Answers

You can add the loading attribute to your image element to lazy-load the images. A complete explainer guide on this attribute can be found on web.dev.

In your case it would probably look as follows:

cards.map(card => (
  <img src={SportImages[card.image_ref]} loading="lazy" />
))
5

You can use this library called react-lazy-load-image-component Import the LazyLoadImage component then use it the render you images

cards.map(card => (
     <LazyLoadImage src={SportImages[card.image_ref]} {...props}/>
  ))

You can also add an effect when lazy loading the images. You can check the documentation of the library here

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Maya Lin-Takahashi

Maya Lin-Takahashi

Consumer Tech & Gadget Reviewer

Maya is a hardware enthusiast who tests and reviews smart home devices, smartphones, wearables, and audio gear. She focuses on practical consumer value and build quality.

Share this article
Twitter Facebook Pinterest