Improving web performance is crucial for providing a better user experience. In this DevTip, we'll explore how to implement lazy loading for images and videos in React applications to enhance performance and reduce initial load times.

Why lazy loading matters

Lazy loading defers the loading of non-critical resources at page load time. Instead, these resources are loaded when they are needed. This technique significantly improves the initial load time, especially for pages with many images or videos.

Setting up a React application

We'll start by setting up a basic React application. If you haven't already, you can create a new React app using Create React App:

npx create-react-app my-app
cd my-app
npm start

Implementing lazy loading for images

Using native lazy loading

Modern browsers support the loading attribute for images, which can be set to lazy:

<img src="path/to/image.jpg" alt="Description" loading="lazy" />

This is the simplest way to implement lazy loading for images without additional libraries.

Using a React lazy loading library

For more advanced use cases, you might consider using a library like react-lazyload:

First, install the library:

npm install react-lazyload

Then, import and use it in your component:

import React from 'react'
import LazyLoad from 'react-lazyload'

function ImageGallery() {
  return (
    <div>
      <LazyLoad height={200} offset={100}>
        <img src="path/to/image1.jpg" alt="Description 1" />
      </LazyLoad>
      <LazyLoad height={200} offset={100}>
        <img src="path/to/image2.jpg" alt="Description 2" />
      </LazyLoad>
      {/* Add more images as needed */}
    </div>
  )
}

export default ImageGallery

Implementing lazy loading for videos

Videos can also benefit from lazy loading. Here's how you can implement it.

Using React suspense and dynamic imports

React's Suspense and dynamic imports can be used to lazy load components.

import React, { Suspense } from 'react'

const VideoComponent = React.lazy(() => import('./VideoComponent'))

function App() {
  return (
    <div>
      <Suspense fallback={<div>Loading video...</div>}>
        <VideoComponent />
      </Suspense>
    </div>
  )
}

export default App

Inside VideoComponent.js:

import React from 'react'

function VideoComponent() {
  return (
    <video controls>
      <source src="path/to/video.mp4" type="video/mp4" />
      Your browser does not support the video tag.
    </video>
  )
}

export default VideoComponent

Utilizing intersection observer API

For more control, you can use the Intersection Observer API to load videos when they enter the viewport.

First, install a hook library like react-intersection-observer:

npm install react-intersection-observer

Then, use it in your component:

import React from 'react'
import { useInView } from 'react-intersection-observer'

function LazyVideo() {
  const { ref, inView } = useInView({
    triggerOnce: true,
    threshold: 0.25,
  })

  return (
    <div ref={ref}>
      {inView ? (
        <video controls>
          <source src="path/to/video.mp4" type="video/mp4" />
          Your browser does not support the video tag.
        </video>
      ) : (
        <div style={{ height: '300px', background: '#ccc' }}>Loading video...</div>
      )}
    </div>
  )
}

export default LazyVideo

Best practices

  • Use Placeholder Images: Display low-resolution placeholders or blurred images while the high-resolution image loads.
  • Optimize Media Files: Ensure that images and videos are optimized for the web to reduce load times.
  • Combine Techniques: Use lazy loading in combination with a Content Delivery Network (CDN) like Transloadit to deliver media efficiently.

Conclusion

Implementing lazy loading for images and videos in React applications significantly improves performance and user experience. By deferring the loading of non-critical resources, you ensure faster initial load times and a smoother browsing experience for your users.

At Transloadit, we offer solutions to optimize and deliver your media efficiently. Consider integrating our services to further enhance your application's performance.