Next.js offers an Image component that automatically optimizes images for better performance and user experience. This component provides properties to control image loading (loading or priority), size and layout (width, height, layout), and placeholders (placeholder, blurDataURL). These features help improve loading times and visual stability by efficiently handling image rendering and responsiveness.
Some of the Image components are mentioned below that help image optimization in Next.js:
- Image Loading Behavior: The ‘loading’ property controls how images load. By default, it uses “lazy” loading, which loads images as they become visible during scrolling. For crucial images, you can use “eager” loading or the ‘priority’ property.
- Example:
<Image
src="/example.png"
alt="Example"
width={500}
height={300}
loading="eager"
// or
priority={true}
/>
- Image Sizing and Layout: Always specify image dimensions to improve Cumulative Layout Shift (CLS). If dimensions are unknown, use ‘layout=”fill”‘, which makes the image respond to its parent container’s dimensions. The ‘layout’ property offers four options: “fill”, “intrinsic”, “responsive”, and “fixed”.
When using ‘layout=”fill”‘, the ‘objectFit’ property determines how the image resizes within its container. Options include “contain”, “cover”, “fill”, and “none”.
Example:
<Image src="/example.png" alt="Example" layout="fill" objectFit="contain" />
- Placeholders and Loading Indicators: The ‘placeholder’ property allows for a temporary image or loading indicator while the main image loads. It can be set to “blur” or “empty”. When using “blur”, you can provide a base64-encoded image as a blurred placeholder.
- Example:
<Image
src="/example.png"
alt="Example"
width={600}
height={450}
placeholder="blur"
blurDataURL="data:image/png;base64,..."
/>
- Image Quality: The ‘quality’ property allows you to set the image quality, with values ranging from 1 to 100. The default is 75.
- Example:
<Image
src="/example.png"
alt="Example"
width={500}
height={550}
quality={100}
/>