Next.js
/Advanced
Dynamic Imports
Definition
A technique to manually force Code Splitting within a SINGLE page, delaying the download of a heavy component until the exact moment it is needed.
Explain Like I'm New
Your homepage has a massive '3D Interactive Map' at the very bottom. If you import it normally, the browser downloads the heavy 3D library immediately, slowing down the initial page load. With a dynamic import, you tell the browser: 'Do NOT download this map code until the user actually scrolls down and sees it.'
Real World Example
Loading a heavy rich-text Markdown Editor component ONLY when the user clicks the 'Reply' button.
Common Use Cases
- •Heavy third-party libraries
- •Modals
- •Components below the fold
Interactive Example
import dynamic from 'next/dynamic'; import { useState } from 'react'; // 1. Manually Code-Split the heavy editor component. // It will NOT be included in the initial page load bundle! const HeavyMarkdownEditor = dynamic(() => import('./HeavyEditor'), { loading: () => <p>Loading editor...</p>, ssr: false, // Optional: Force it to only ever run on the client browser }); export default function CommentSection() { const [showEditor, setShowEditor] = useState(false); return ( <div> <button onClick={() => setShowEditor(true)}>Reply</button> {/* 2. The browser only downloads the Editor's JS code when this turns true! */} {showEditor && <HeavyMarkdownEditor />} </div> ); }
Interview Questions
basic
- What Next.js function is used to create a dynamic import?
intermediate
- Why is it highly recommended to provide a `loading` fallback when using dynamic imports?