Blog>
Snippets

Caching Images with the Next.js Image Component

Utilize the built-in Image component in Next.js to cache images for faster load times using the 'priority' and 'placeholder' props.
import Image from 'next/image';

function MyImageComponent() {
  return (
    <div>
      <Image
        src='/path-to-your-image.jpg' // Static import of image file
        alt='Description of the Image'
        width={500} // Width of the image in pixels
        height={300} // Height of the image in pixels
        priority // Indicates that the image should be considered high priority
        placeholder='blur' // Indicates to use a blur-up image loading effect
        blurDataURL='data:image/png;base64,...' // Base64 encoded image used as placeholder
      />
    </div>
  );
}

export default MyImageComponent;
This Next.js component uses the built-in Image component to display an image. The 'priority' prop tells Next.js to preload this image in the browser, giving it higher priority during the initial page load. The 'placeholder' prop set to 'blur' enables a blur-up effect to initially show a tiny blurred version of the image while the full image is being loaded. 'blurDataURL' must contain a valid base64 encoded image string, which will be used as the placeholder.
/* Add to your CSS file or a style tag to style the image container */
.my-image-container {
  width: 500px; // Must be the same as the width you set on the Image component
  position: relative;
  overflow: hidden;
}
This CSS styles a container for the Next.js Image component with the same fixed width as the Next.js Image component, creating a space for the image that maintains the layout during loading.