Optimizing Media: Image Component

▲ Next.js Lesson 8 Intermediate

The Next.js Image component (next/image) extends standard HTML image elements, automatically optimizing images to improve core web vitals.

1 Auto sizing, format compression and layout shifts

Key optimizations provided by the Image component include:

  • Modern Format Compression: Automatically converts images to compressed formats (like WebP or AVIF) based on browser support.
  • Prevent Layout Shifts: Requires explicit width and height configurations to reserve layout space, preventing Cumulative Layout Shift (CLS) as images load.
  • Responsive Sizes: Uses the sizes attribute to serve appropriately sized images to different device screens.
  • Lazy Loading: Images are lazy-loaded by default, loading only when they enter the viewport.
2 Using the Image Component

Let's check how to implement the Image component:

React — Image Component
import Image from 'next/image';

export default function Banner() {
  return (
    <div class="banner-wrapper">
      <!-- Optimized responsive image -->
      <Image 
        src="/assets/featured.jpg" 
        alt="Featured Product" 
        width={800} 
        height={400}
        priority // loads immediately without lazy-loading (useful for LCP images)
        sizes="(max-width: 768px) 100vw, 800px"
      />
    </div>
  );
}
3 Code Challenge
Challenge: Write a layout that uses an image with the fill attribute configuration. Explain why setting the parent container to position: relative is required when using this layout mode.