4 min read
ā¢Question 26 of 47mediumHow to use dynamic imports in Next.js?
Code splitting with dynamic imports.
What You'll Learn
- next/dynamic usage
- Loading states
- SSR control
Basic Dynamic Import
code.txtTSX
import dynamic from 'next/dynamic';
const HeavyComponent = dynamic(() => import('./HeavyComponent'));
export default function Page() {
return (
<div>
<h1>My Page</h1>
<HeavyComponent />
</div>
);
}With Loading State
code.txtTSX
const Chart = dynamic(() => import('./Chart'), {
loading: () => <p>Loading chart...</p>,
});Disable SSR
code.txtTSX
// For components that use browser APIs
const Map = dynamic(() => import('./Map'), {
ssr: false,
});
// Useful for:
// - Libraries that access window/document
// - Heavy client-only components
// - Third-party widgetsNamed Exports
code.txtTSX
const Modal = dynamic(() =>
import('./components').then((mod) => mod.Modal)
);With Suspense
code.txtTSX
import { Suspense } from 'react';
import dynamic from 'next/dynamic';
const Comments = dynamic(() => import('./Comments'));
export default function Post() {
return (
<article>
<h1>Post Title</h1>
<Suspense fallback={<p>Loading comments...</p>}>
<Comments />
</Suspense>
</article>
);
}