Lazy Loading Images In Next.js


We have all heard this term before. Lazy Loading. What is it anyways?

Lazy loading postpones the loading of resources on a page, in this case an image, until they are actually required. Rather than loading these resources as soon as the page loads, as is usually the case, they are delayed until the user need them. They have numerous advantages. We can make our web pages load really quickly with lazy loading. In this guide, we will cover how to lazy load images using Next.js.

Next.js comes default with an Image component. Lazy loading is enabled by default in the Next.js Image component. It is not only useful to the end-user, but it is also beneficial to the server because it does not have to execute image generation for images that may or may not be required.

Installation and Setup

You can create a new Next.js application using the following command:

npx create-next-app lazy-load-images

Let's start the application by running the following command

npm run dev
# or
yarn dev

We are running our application in the development server. Open your browser and navigate to localhost:3000.

Lazy Loading

Add a new image file to the public directory. In the pages directory, create a new file lazy-load.js. This will be our Next.js page.

Add the following to the fil

export default function ImagePage() {
    return (
        <h1>Image Page</h1>

Visit localhost:3000/lazy-load to preview the page. Now that the page has rendered succesfully, we can continue to implement lazy loading.

First import the Image component from Next.js

import Image from "next/image";

Next, replace the <h1> tag with this the Image Component


Now preview it in the browser to see the results. Add a lot of images and see lazy loading in action as you scroll.