Image
~10 mins
- nextjs
Image
<img
src="/hero.png"
alt="Screenshots of the dashboard project showing desktop version"
/>
- However, this means you have to manually:
- Ensure your image is responsive on different screen sizes.
- Specify image sizes for different devices.
- Prevent layout shift as the images load.
- Lazy load images that are outside the user's viewport.
- Image Optimization is a large topic in web development that could be considered a specialization in itself.
- Instead of manually implementing these optimizations, you can use the next/image component to automatically optimize your images.
Image Component
- The
<Image>Component is an extension of the HTML<img>tag, and comes with automatic image optimization, such as:
- Preventing layout shift automatically when images are loading.
- Resizing images to avoid shipping large images to devices with a smaller viewport.
- Lazy loading images by default (images load as they enter the viewport).
- Serving images in modern formats, like WebP and AVIF, when the browser supports it.
import Image from 'next/image';
export default function Page() {
return (
<Image
src="/profile.png"
width={500}
height={500}
alt="Picture of the author"
/>
);
}
- It's good practice to set the width and height of your images to avoid layout shift, these should be an aspect ratio identical to the source image.