DEV Community

Cover image for Next.js Image Component - Automatic Image Optimization
Chris Sev
Chris Sev

Posted on

Next.js Image Component - Automatic Image Optimization

Next.js 10 came out recently and with it brought the Next.js Image Component.

Next.js Image Component Features

Alt Text

The main features of the Next.js Image Component are that it requires very little configuration to immediately optimize our images.

Main features include:

  • Automatic Image Optimization: Deliver the right optimized image and format
  • Lazy loading: An image will only load when it is within the viewport
  • Automatic Resizing (srcset): Deliver the correct size image based on the browser size

Image Optimization on-demand

The cool thing about Next's Image Optimization is that it all happens when a user requests the page, not when we build our static sites.

Instead of optimizing images at build time, Next.js optimizes images on-demand, as users request them. Unlike static site generators and static-only solutions, your build times aren't increased, whether shipping 10 images or 10 million images.

To Use the Next.js Image Component

Replace your <img> tags with the Next.js <Image /> component. Required properties are:

  • src
  • width
  • height

Let's say we have an image located in our Next.js project at /public/images/mountains.jpg. Instead of having an tag:

<img src="/images/mountains.jpg" />
Enter fullscreen mode Exit fullscreen mode

Replace with the Next.js Image Component

import Image from 'next/image';

export default function Home() {
  return (
    <Image 
      src="/images/mountains.jpg" 
      width="1920" 
      height="1080"
    />
  )
}
Enter fullscreen mode Exit fullscreen mode

Our image will be optimized and will be a smaller size.

Delivering Resized Images

To deliver a Next.js Image Component with a resized image, add a layout property to your component.

<Image 
  src="/images/mountains.jpg" 
  width="1920" 
  height="1080"
  layout="responsive"
/>
Enter fullscreen mode Exit fullscreen mode

You should see even smaller file sizes now.

Top comments (0)