The <Image>
component from next/image
optimizes image loading, improves performance, and provides built-in features such as lazy loading, automatic resizing, and responsive behavior. It is preferred over the standard <img>
tag for handling images in Next.js applications.
Basic Usage
import Image from "next/image";
export default function Example() {
return <Image src="/example.jpg" alt="Example" width={500} height={300} />;
}
src
: Specifies the image path (supports local and remote URLs).alt
: Provides an accessible description of the image.width
and height
: Define the image dimensions, required for static images.Automatic Optimization
Using Remote Images
For external images, the domain must be added to next.config.js
.
module.exports = {
images: {
remotePatterns: [
{
protocol: "https",
hostname: "example.com",
},
],
},
};
<Image src="<https://example.com/image.jpg>" alt="Remote Image" width={500} height={300} />
Responsive Images
For images that need to scale within a container, use the fill
prop instead of width
and height
.
<div className="relative w-64 h-40">
<Image src="/example.jpg" alt="Example" fill className="object-cover" />
</div>
object-cover
ensures the image maintains aspect ratio without distortion.Blur Placeholder for Better UX