Next.jsMedium

What is React.lazy and how does it work with Next.js?

React.lazy(() => import("./Comp")) defines a component whose code is loaded the first time it renders, suspending until the module arrives, so it must sit inside <Suspense>. In Next.js it works in Client Components, but next/dynamic is usually preferred because it adds a loading option, ssr: false and better integration with SSR and preloading.

How React.lazy works

  1. The import function runs on first render.
  2. The component suspends; the nearest <Suspense> shows its fallback.
  3. When the module resolves, React renders its default export.
  4. The result is cached; later renders are immediate.

Constraints

  • The module must have a default export that is a component (wrap named exports: .then((m) => ({ default: m.Chart }))).
  • Define it at module scope.
  • Needs a <Suspense> boundary.
  • Used in Server Components it gives no client code-splitting benefit; use it in Client Components.

next/dynamic vs React.lazy

React.lazynext/dynamic
Needs explicit <Suspense>YesNo (built in)
Loading component optionNoloading
Disable SSRNossr: false
Named exportsManual wrapper.then((m) => m.Named)

SSR behavior

Both server-render the component on first load when SSR is enabled, so the HTML contains it, then load the chunk for hydration.

When to choose React.lazy

Code shared with non-Next React apps, or libraries that already expect it.

Code example

tsx
1// app/settings/advanced.tsx
2"use client";
3
4import { lazy, Suspense, useState } from "react";
5
6// Default export required
7const AdvancedPanel = lazy(() => import("./advanced-panel"));
8// Named export wrapped into a default
9const AuditLog = lazy(() => import("./audit").then((m) => ({ default: m.AuditLog })));
10
11export function Advanced() {
12 const [open, setOpen] = useState(false);
13
14 return (
15 <section>
16 <button onClick={() => setOpen((o) => !o)}>Advanced settings</button>
17 {open && (
18 <Suspense fallback={<p>Loading…</p>}>
19 <AdvancedPanel />
20 <AuditLog />
21 </Suspense>
22 )}
23 </section>
24 );
25}
26
27// next/dynamic equivalent with fewer moving parts:
28// const AdvancedPanel = dynamic(() => import("./advanced-panel"), { loading: () => <p>Loading…</p> });

Practice this question

Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the Next.js set.

Open in study app