Lazy Loading Components in Next.js

In Next.js, lazy loading (also known as code splitting) allows you to load components or images only when they are needed, which can significantly improve performance, especially for larger applications.

Lazy Loading Components in Next.js

You can lazy load components using React.lazy() or Next.js’s dynamic() function.

1. Using React.lazy():

React’s lazy() function allows you to import components dynamically. However, you’ll need to use Suspense to provide a fallback UI while the component is loading.

import React, { Suspense } from 'react';

const LazyComponent = React.lazy(() => import('./LazyComponent'));

export default function Home() {
  return (
    <div>
      <Suspense fallback={<div>Loading...</div>}>
        <LazyComponent />
      </Suspense>
    </div>
  );
}

2. Using next/dynamic():

Next.js provides its own dynamic() function, which gives more control over lazy loading. It’s often preferred because it supports server-side rendering and has options for loading fallback components.

import dynamic from 'next/dynamic';

const LazyComponent = dynamic(() => import('./LazyComponent'), {
  loading: () => <p>Loading...</p>, // Optional loading indicator
  ssr: false, // Disable server-side rendering for this component
});

export default function Home() {
  return (
    <div>
      <LazyComponent />
    </div>
  );
}

Lazy Loading Images

Next.js also provides a built-in Image component that automatically optimizes and lazy loads images.

import Image from 'next/image';

export default function Home() {
  return (
    <div>
      <Image
        src="/image.jpg" 
        alt="Example image"
        width={500}
        height={300}
        loading="lazy" // Ensures lazy loading
      />
    </div>
  );
}

Benefits of Lazy Loading

  • Performance: Decreases the initial load time by only loading components and images when they enter the viewport.
  • Bandwidth: Reduces bandwidth consumption by loading assets on demand.

Leave a comment

Your email address will not be published. Required fields are marked *