#1 Data Analytics Program in India
₹2,499₹1,499Enroll Now
4 min read
•Question 4 of 47easy

How to optimize images in Next.js?

Using the Image component for optimization.

What You'll Learn

  • Image component usage
  • Optimization features
  • Responsive images

Basic Usage

code.txtTSX
import Image from 'next/image';

export default function Avatar() {
  return (
    <Image
      src="/profile.jpg"
      alt="Profile"
      width={200}
      height={200}
    />
  );
}

Remote Images

code.txtTSX
// next.config.js - configure allowed domains
module.exports = {
  images: {
    remotePatterns: [
      {
        protocol: 'https',
        hostname: 'example.com',
      },
    ],
  },
};

// Usage
<Image
  src="https://example.com/photo.jpg"
  alt="Remote"
  width={500}
  height={300}
/>

Fill Mode

code.txtTSX
// Fill parent container
<div style={{ position: 'relative', width: '100%', height: '400px' }}>
  <Image
    src="/hero.jpg"
    alt="Hero"
    fill
    style={{ objectFit: 'cover' }}
  />
</div>

Responsive Sizes

code.txtTSX
<Image
  src="/photo.jpg"
  alt="Photo"
  fill
  sizes="(max-width: 768px) 100vw, 50vw"
/>

Priority Loading

code.txtTSX
// Load immediately (above the fold)
<Image
  src="/hero.jpg"
  alt="Hero"
  width={1200}
  height={600}
  priority
/>