Performance is a critical factor in modern web applications.
In this lesson, you will learn how Next.js optimizes images by default and how to use built-in tools to deliver fast and efficient user experiences.
Why Image Optimization Matters
Images often represent the largest portion of page weight.
Poor image handling can cause:
- Slow page loads
- High bounce rates
- Bad Core Web Vitals scores
- Poor SEO performance
Next.js provides automatic image optimization to solve these issues.
The next/image Component
Next.js includes the Image component for optimized images.
Key benefits:
- Automatic resizing
- Lazy loading by default
- Modern image formats
- Responsive behavior
Using next/image is recommended over standard <img> tags.
Basic Image Usage
Example usage of the Image component:
import Image from "next/image";
export default function Page() {
return (
<Image
src="/hero.png"
alt="Hero image"
width={600}
height={400}
/>
);
}Width and height are required to prevent layout shifts.
Static Images
Images inside the public folder can be referenced directly.
Example:
- public/logo.png
Usage:
<Image src="/logo.png" alt="Logo" width={120} height={60} />Static assets are served efficiently by Next.js.
Remote Images
You can also optimize images hosted on external domains.
First, configure allowed domains:
module.exports = {
images: {
domains: ["images.example.com"]
}
};Then use the Image component normally.
Lazy Loading Explained
By default, next/image uses lazy loading.
This means:
- Images load only when visible
- Faster initial page load
- Reduced bandwidth usage
Lazy loading improves performance automatically without extra setup.
Priority Images
For important images (like hero banners), you can prioritize loading.
<Image
src="/hero.png"
alt="Hero"
width={800}
height={500}
priority
/>Use this sparingly to avoid blocking rendering.
Image Sizes and Responsiveness
Use the sizes prop for responsive images.
<Image
src="/banner.png"
alt="Banner"
fill
sizes="(max-width: 768px) 100vw, 50vw"
/>This allows the browser to choose the best image size.
Other Performance Optimizations
Next.js improves performance through:
- Automatic code splitting
- Server Components
- Built-in caching
- Static generation
These features reduce JavaScript size and improve load times.
Common Image Mistakes
Avoid these mistakes:
- Using
<img>instead of next/image - Missing width and height
- Overusing priority images
- Serving oversized images
Correct image usage directly impacts performance scores.
Summary
In this lesson, you learned:
- Why image optimization is important
- How next/image works
- Using static and remote images
- Lazy loading and priority images
- Responsive image techniques
- Performance best practices
In the next lesson, we will explore styling in Next.js and learn how to manage styles effectively in Next.js applications.