Blog>
Snippets

Utilizing the next/dynamic Function for Lazy Loading Modules

Utilize the next/dynamic function to import modules only when they are required, reducing the initial bundle size.
import dynamic from 'next/dynamic';

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

export default function HomePage() {
  return (
    <div>
      <h1>Welcome to Next.js!</h1>
      {/* LazyComponent will only be loaded when this part of the UI is rendered */}
      <LazyComponent />
    </div>
  );
}
In this code, 'next/dynamic' is being imported to allow for lazy loading of a component named 'LazyComponent'. The dynamic function accepts a function that returns a promise of the module to be imported. In this case, 'import('./LazyComponent')' is the module being lazily loaded. The 'loading' option provides a placeholder component to be displayed while the LazyComponent is being loaded. The 'ssr' option is set to false to disable server-side rendering of the component, meaning it will only be loaded on the client side.