Blog>
Snippets

Dynamic Import for Component Splitting

Demonstrate how to use Next.js dynamic imports for splitting components and reducing the initial load time.
import dynamic from 'next/dynamic';

// Dynamic import of a component only when it's required
const DynamicComponent = dynamic(() => import('./DynamicComponent'), {
  /* Optionally include loading: () => <p>Loading...</p> */
  ssr: false
});

export default function Home() {
  return (
    <div>
      <h1>Welcome to the Home Page</h1>
      {/* Render the dynamically-imported component */}
      <DynamicComponent />
    </div>
  );
}
This code snippet demonstrates how to import a component dynamically in Next.js using the 'dynamic' function from 'next/dynamic'. 'DynamicComponent' will only be loaded when it's needed, potentially reducing the initial load time of your page. The 'ssr: false' option disables server-side rendering for this component.