Labs ICT
โญ Pro Login

Image Optimization

Image Optimization

Next.js provides an Image component that automatically optimizes images for better performance. It handles resizing, format conversion, and lazy loading out of the box.

Think of the Image component as a personal assistant for your images. It automatically compresses them, serves them in modern formats, and only loads them when needed.

Using the Image Component

Import the Image component from next/image and use it in your components:

import Image from 'next/image';

export default function Hero() {
  return (
    <div>
      <Image
        src="/hero.jpg"
        alt="Hero image"
        width={1200}
        height={600}
        priority
      />
    </div>
  );
}

The width and height props are required. They help Next.js reserve space and prevent layout shifts.

Remote Images

You can also optimize remote images by configuring the domains in your next.config.js:

// next.config.js
module.exports = {
  images: {
    remotePatterns: [
      {
        protocol: 'https',
        hostname: 'example.com',
      },
    ],
  },
};

This allows you to optimize images from external sources like CDNs or APIs.

Image Properties

The Image component supports many useful properties:

fill: Makes the image fill its parent container.

priority: Loads the image immediately (for above-the-fold images).

placeholder: Shows a placeholder while the image loads.

sizes: Specifies different image sizes for different viewports.

<Image
  src="/photo.jpg"
  alt="A beautiful photo"
  fill
  sizes="(max-width: 768px) 100vw, 50vw"
  placeholder="blur"
/>

Best Practices

Follow these guidelines for optimal image performance:

Use priority for LCP: Mark your largest contentful paint image with priority.

Specify dimensions: Always provide width and height to prevent layout shifts.

Use modern formats: Next.js automatically serves WebP and AVIF formats.

Lazy load off-screen images: The Image component lazy loads by default.

Proper image optimization can significantly improve your Core Web Vitals scores.

๐Ÿงช Quick Quiz

What is the Image component in Next.js used for?