How to use the useInView hook for lazy loading images in Next.js



Image not found!!

To implement lazy loading of images in a Next.js application using the useInView hook, you can follow these steps:

  1. Install the necessary dependencies:
bash
npm install react-intersection-observer
  1. Create a custom hook for lazy loading images:
jsx
// components/useLazyLoad.js import { useInView } from 'react-intersection-observer'; import { useEffect, useState } from 'react'; const useLazyLoad = () => { const [ref, inView] = useInView({ triggerOnce: true, }); const [isLoaded, setIsLoaded] = useState(false); useEffect(() => { if (inView) { const img = new Image(); img.src = ref.current.dataset.src; img.onload = () => { ref.current.src = img.src; setIsLoaded(true); }; } }, [inView, ref]); return { ref, isLoaded }; }; export default useLazyLoad;
  1. Use the custom hook in your Next.js component:
jsx
// components/ImageLazyLoad.js import useLazyLoad from './useLazyLoad'; const ImageLazyLoad = ({ src, alt }) => { const { ref, isLoaded } = useLazyLoad(); return ( <img ref={ref} data-src={src} alt={alt} style={{ opacity: isLoaded ? 1 : 0, transition: 'opacity 0.3s' }} /> ); }; export default ImageLazyLoad;
  1. Implement the lazy-loading image component in your page:
jsx
// pages/index.js import ImageLazyLoad from '../components/ImageLazyLoad'; const images = [ { src: '/path/to/image1.jpg', alt: 'Image 1' }, { src: '/path/to/image2.jpg', alt: 'Image 2' }, // Add more images as needed ]; const Home = () => { return ( <div> <h1>Lazy Loading Images in Next.js</h1> {images.map((image, index) => ( <ImageLazyLoad key={index} src={image.src} alt={image.alt} /> ))} </div> ); }; export default Home;

This example uses the react-intersection-observer library to determine when the image is in the viewport. The custom useLazyLoad hook handles the lazy loading of images, and the ImageLazyLoad component wraps the actual img tag with the lazy loading logic.

Make sure to replace the placeholder image paths in the images array with the actual paths of your images. This setup will only load the images when they are about to become visible in the viewport, improving page load performance.