tezvyn:

next/dynamic: Defer Loading Heavy Components

AI-drafted, machine-checkedSource: nextjs.orgintermediate

next/dynamic splits a component into its own file, loading it only when needed to shrink your initial bundle. Use it for heavy components below the fold or browser-only libraries. The footgun: forgetting a loading state causes layout shifts.

WHY IT EXISTS By default, Next.js bundles all the code needed for a page into a single JavaScript file. For complex pages with many components, this file can become very large, leading to slow initial page loads. Dynamic imports solve this by breaking the code into smaller, manageable chunks that are loaded on demand.

THE MENTAL MODEL next/dynamic is a form of code splitting specifically for React components. Imagine your app is a toolkit. Instead of carrying every single tool to a job, you bring a small, essential kit and have the specialized, heavy tools delivered only when you need them. This makes you faster and more efficient upfront. next/dynamic does this for your JavaScript bundles.

HOW IT WORKS You wrap a standard component import in the dynamic() function from next/dynamic. Next.js's bundler sees this and creates a separate JavaScript file (a chunk) for that component and its dependencies. When your application logic requires rendering the dynamic component, Next.js fetches this chunk from the server and then mounts the component. You can provide a placeholder loading component to display while the chunk is being downloaded.

WHEN TO USE IT Use next/dynamic for components that are large and not critical for the initial paint, such as a video player, a heavy data visualization library (like D3), or a rich text editor. It's also the go-to solution for integrating components that depend on browser-specific APIs (like window or document), as you can disable server-side rendering for them.

WHEN NOT TO USE IT Avoid using it for small, simple components that are visible above the fold. The overhead of an extra network request for a tiny component can negate any benefits and might even slow down rendering. It's a tool for significant performance gains, not micro-optimizations.

ONE CANONICAL EXAMPLE To use a mapping library like Leaflet, which relies on the window object, you must prevent it from rendering on the server. You would import it like this: const Map = dynamic(() => import('../components/Map'), { ssr: false, loading: () => Loading map... });. This tells Next.js to never render the map on the server and to show a "Loading map..." message on the client while the component's code is fetched.

Read the original → nextjs.org

Get five bites like this every day.

Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.