0
0
NextjsHow-ToBeginner · 3 min read

How to Lazy Load Components in Next.js for Faster Pages

In Next.js, you can lazy load components using the dynamic function from next/dynamic. This lets you load components only when needed, improving page speed by splitting code automatically.
📐

Syntax

Use the dynamic function to import components lazily. It takes a function that returns a dynamic import() call. Optionally, you can provide a loading component to show while the lazy component loads.

  • dynamic(() => import('./MyComponent')): Lazy loads MyComponent.
  • loading option: Shows a placeholder while loading.
javascript
import dynamic from 'next/dynamic';

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

Example

This example shows a button that toggles the display of a lazily loaded component. The component only loads when the user clicks the button, improving initial page load speed.

javascript
import { useState } from 'react';
import dynamic from 'next/dynamic';

const LazyComponent = dynamic(() => import('./LazyComponent'), {
  loading: () => <p>Loading component...</p>,
  ssr: false
});

export default function Home() {
  const [show, setShow] = useState(false);

  return (
    <main>
      <button onClick={() => setShow(!show)}>
        {show ? 'Hide' : 'Show'} Lazy Component
      </button>
      {show && <LazyComponent />}
    </main>
  );
}
Output
<button>Show Lazy Component</button>
⚠️

Common Pitfalls

  • Not disabling SSR (ssr: false) when the component depends on browser-only APIs can cause errors.
  • Forgetting to provide a loading fallback can cause blank spaces during loading.
  • Importing components statically defeats lazy loading benefits.
javascript
/* Wrong way: static import (no lazy loading) */
import MyComponent from './MyComponent';

export default function Page() {
  return <MyComponent />;
}

/* Right way: dynamic import with loading fallback */
import dynamic from 'next/dynamic';

const MyComponent = dynamic(() => import('./MyComponent'), {
  loading: () => <p>Loading...</p>,
  ssr: false
});

export default function Page() {
  return <MyComponent />;
}
📊

Quick Reference

  • Import dynamic: import dynamic from 'next/dynamic'
  • Basic lazy load: dynamic(() => import('./Component'))
  • Loading fallback: Use loading option to show a placeholder
  • Disable SSR: Use ssr: false if component uses browser-only features

Key Takeaways

Use Next.js dynamic import to lazy load components and improve page speed.
Provide a loading fallback to avoid blank UI during component loading.
Disable server-side rendering with ssr: false for browser-only components.
Lazy loading delays component code download until needed, reducing initial bundle size.
Avoid static imports if you want to benefit from lazy loading.