Search⌘ K
AI Features

Working with next/image

Explore how to use the Next.js next/image component to optimize images efficiently. Understand its automatic resizing, compression, modern format serving, lazy loading, and techniques for responsive images. Learn to eliminate layout shifts by defining image dimensions, use placeholders for smooth loading, and configure remote image sources securely. By the end, you'll be able to replace traditional img tags with next/image to enhance performance and user experience in your Next.js applications.

Large, unoptimized images can slow down a site and create a frustrating user experience. We’ve all seen that annoying “page jump” when a big image suddenly loads. This is called cumulative layout shift (CLS), and it’s one of the main problems the next/image component solves.

The next/image component extends the HTML <img> element and automatically handles tasks like resizing, optimization, and serving images in modern formats, giving users a smoother experience.

Let’s explore the key features of the next/image component and how to use it effectively!

How does next/image optimize

The Image component from next/image handles image optimization out of the box. When we use it, Next.js performs optimizations such as:

  • Resizing images to fit each device and viewport.

  • Compressing images without sacrificing quality.

  • Serving modern formats like WebP for better performance.

  • Lazy loading images by default, loading them only when they enter the viewport.

  • ]

This all happens automatically by simply using the component.

How to use next/image

To use the Image component, we first need to import it from next/image:

import Image from 'next/image';

Then, we use it in our components just like a regular <img> tag. The src prop can be either a string for a remote image or a statically imported image file.

Here’s a basic example of using Image with a local file. Typically, the component requires src, alt, width, and height props to function properly:

export default function RootLayout({ children }) {
  return (
    <html lang="en">
      <body>{children}</body>
    </html>
  );
}
Using a local image with next/image
  • Line 2: We statistically import the local image file.

  • Line 9: The image file imported from the public directory is assigned to the src prop. Because of the static import, Next.js can analyze the image at build time for optimizations.

  • Line 10: The alt prop provides an accessible description of the image for screen readers.

  • Lines 11–12: The width and height props define the image’s dimensions in pixels and set its default rendered size. The rendered size can be overridden by any applied CSS.

More importantly, in Next.js, the width and ...