0 day streak
javascript / beginner
Snippet

Lazy Loading Heavy Components with Dynamic Imports

Dynamic imports in Next.js defer loading non-critical JavaScript until required, optimizing initial bundle size and improving page performance.

snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
// app/dashboard/page.js
import dynamic from 'next/dynamic';
// Load chart component only when needed on client side
const HeavyChart = dynamic(() => import('../components/HeavyChart'), {
loading: () => <p>Loading chart...</p>
});
export default function Dashboard() {
return <HeavyChart />;
}
nextjs
Breakdown
1
import dynamic from 'next/dynamic';
Imports the dynamic component loader module from Next.js.
2
const HeavyChart = dynamic(() => import('../components/HeavyChart'), {
Configures dynamic loading for a heavy component module on demand.
3
loading: () => <p>Loading chart...</p>
Provides a fallback loading UI component while JavaScript resources download.
4
return <HeavyChart />;
Renders the lazily-loaded dynamic component in the page layout.