Topic 34 of 39
Image Optimization
Overview
The next/image component extends the standard <img> tag to provide automatic size optimization, lazy loading, layout shift prevention, and modern formats like WebP/AVIF. It drastically improves Core Web Vitals.
Syntax
tsx
import Image from 'next/image';
import localPic from '@/public/hero.jpg';
export default function Page() {
return (
<div>
{/* Local image: width/height automatically inferred */}
<Image src={localPic} alt="Hero" priority />
{/* Remote image: must provide width and height */}
<Image
src="https://external.com/photo.jpg"
alt="Remote"
width={500}
height={300}
/>
</div>
);
}Common Pitfalls
- Forgetting to whitelist external domains in
next.config.js. Remote images will fail to load for security reasons otherwise. - Not adding the
priorityprop to images above the fold (like hero images), causing slow LCP (Largest Contentful Paint).
Interview Questions
Q:
How does
next/image prevent Cumulative Layout Shift (CLS)?A:
It requires width and height attributes (or infers them for local images) to reserve the exact space in the DOM before the image loads, preventing content from jumping around.
Real-World Example
Configuring remote image patterns in next.config.js.
example
tsx
// next.config.js
module.exports = {
images: {
remotePatterns: [
{
protocol: 'https',
hostname: 'images.unsplash.com',
},
],
},
};Check Your Knowledge
Test your understanding of Image Optimization with these quick questions.