How to Use Dynamic Import in Next.js for Code Splitting
In Next.js, use
dynamic() from next/dynamic to load components dynamically. This delays loading until the component is needed, improving page speed and user experience.Syntax
The dynamic() function from next/dynamic lets you import components dynamically. You pass it a function that returns an import promise. Optionally, you can provide a loading component to show while loading.
dynamic(() => import('path/to/component')): loads the component dynamically.{ loading: () => <LoadingComponent /> }: shows a placeholder while loading.
javascript
import dynamic from 'next/dynamic'; const DynamicComponent = 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 dynamically imported component. The component loads only when shown, improving initial load speed.
javascript
import { useState } from 'react'; import dynamic from 'next/dynamic'; const DynamicHello = dynamic(() => import('./Hello'), { loading: () => <p>Loading component...</p>, ssr: false }); export default function Home() { const [show, setShow] = useState(false); return ( <div> <button onClick={() => setShow(!show)}> {show ? 'Hide' : 'Show'} Hello Component </button> {show && <DynamicHello />} </div> ); }
Output
<button>Show Hello Component</button>
Common Pitfalls
- Not using
dynamic()and importing components normally defeats the purpose of code splitting. - Forgetting to disable SSR (
ssr: false) when a component uses browser-only APIs causes errors. - Not providing a loading fallback can cause blank space during loading.
javascript
/* Wrong way: normal import loads component immediately */ import Hello from './Hello'; export default function Page() { return <Hello />; // Always loaded upfront } /* Right way: dynamic import with loading fallback and SSR disabled */ import dynamic from 'next/dynamic'; const DynamicHello = dynamic(() => import('./Hello'), { loading: () => <p>Loading...</p>, ssr: false }); export default function Page() { return <DynamicHello />; // Loads on demand }
Quick Reference
Use this cheat sheet to remember key options for dynamic():
| Option | Description | Example |
|---|---|---|
| import function | Function returning import promise | () => import('./Component') |
| loading | Component shown while loading | () => Loading... |
| ssr | Enable or disable server-side rendering | ssr: false |
| suspense | Use React Suspense for loading (Next.js 13+) | suspense: true |
Key Takeaways
Use next/dynamic's dynamic() to load components only when needed.
Provide a loading fallback to improve user experience during load.
Disable SSR with ssr: false if the component uses browser-only features.
Dynamic imports help reduce initial page load and improve performance.
Remember to import dynamic from 'next/dynamic' before using it.