Blog>
Snippets

Loading UI for Image-heavy Pages

Showcase a technique to provide a loading UI for image-heavy pages using Next.js's Image component's 'onLoadingComplete' callback.
import { useState } from 'react';
import Image from 'next/image';

function ImageGallery({ images }) {
  const [loading, setLoading] = useState(true);

  const handleLoadingComplete = () => {
    setLoading(false);
  };

  return (
    <div className='image-gallery'>
      {loading && (<div className='loader'>Loading images...</div>)}
      {images.map((src, index) => (
        <div key={index} className='image-wrapper'>
          <Image
            src={src}
            alt={`Gallery image ${index}`}
            layout='responsive'
            width={100}
            height={100}
            onLoadingComplete={handleLoadingComplete}
          />
        </div>
      ))}
    </div>
  );
}

export default ImageGallery;
This code defines a React functional component using Next.js Image component to display an image gallery. Initially, it shows a loading UI until the 'onLoadingComplete' callback is fired, indicating that an image has finished loading. It uses the useState hook to keep track of the loading state. When the image has loaded, the loading state is set to false, hiding the loading UI.