Blog>
Snippets

Dynamic Import for Component-level Code Splitting

Use Next.js 14's dynamic import feature to split code at a component level, only loading parts of the application when they are needed.
import dynamic from 'next/dynamic';

// Import a component dynamically
const DynamicComponent = dynamic(() => import('./DynamicComponent'));

export default function Home() {
  return (
    <div>
      <h1>Hello, World!</h1>
      {/* Render the dynamic component */}
      <DynamicComponent />
    </div>
  );
}
This code demonstrates the use of Next.js's dynamic function to import a component named DynamicComponent. This component is not loaded until it is required during the rendering of the Home component, providing component-level code splitting.
import dynamic from 'next/dynamic';

// Import a component dynamically with a loading component
const DynamicComponentWithCustomLoading = dynamic(
  () => import('./DynamicComponentWithCustomLoading'),
  { loading: () => <p>Loading...</p> }
);

export default function Home() {
  return (
    <div>
      <h1>Hello, World!</h1>
      {/* Render the dynamic component with custom loading component */}
      <DynamicComponentWithCustomLoading />
    </div>
  );
}
This code shows how to use Next.js dynamic import with a custom loading component. While the DynamicComponentWithCustomLoading is being loaded, a <p>Loading...</p> element will be displayed to the user.
import dynamic from 'next/dynamic';

// Import a component dynamically with SSR disabled
const DynamicComponentNoSSR = dynamic(
  () => import('./DynamicComponentNoSSR'),
  { ssr: false }
);

export default function Home() {
  return (
    <div>
      <h1>Hello, World!</h1>
      {/* Render the dynamic component with no SSR */}
      <DynamicComponentNoSSR />
    </div>
  );
}
This code snippet demonstrates how to disable Server-Side Rendering (SSR) for a specific dynamic component with Next.js. The DynamicComponentNoSSR will only be imported and rendered on the client side.