Nextjs Fundamentals · Optimization & Metadata

Lazy-loading components

`next/dynamic`

Lazy-loading components

Lazy loading defers JavaScript until it is needed, shrinking the initial bundle. next/dynamic is a composite of React.lazy() and <Suspense>, and it works in both the app and pages directories.

Call dynamic with a function that imports a component:

'use client';

import dynamic from 'next/dynamic';

const ComponentA = dynamic(() => import('../components/A'));
const ComponentB = dynamic(() => import('../components/B'));
const ComponentC = dynamic(() => import('../components/C'), { ssr: false });

ComponentA loads immediately but in a separate client bundle. ComponentB loads on demand — render it conditionally. Passing { ssr: false } skips server prerendering, and { loading: () => <p>Loading…</p> } supplies a fallback.

The key distinction: Server Components are already code-split and streamed, so next/dynamic is for Client Components and imported libraries. ssr: false is only allowed inside a Client Component; using it in a Server Component is an error.

You can also lazy-load a named export with .then((mod) => mod.Hello).

In short: use next/dynamic to defer Client Components and libraries until they are needed.

You are about to answer a short quiz on next/dynamic.

  1. next/dynamic lazy-loads Client Components and imported libraries.
  2. Pass { ___: false } to next/dynamic to skip server prerendering.
  3. next/dynamic is mainly needed for Server Components, which are not code-split by default.
  4. next/dynamic is a composite of React.lazy() and ___.
  5. The ssr: false option is only allowed inside a Client Component.