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
- The import function runs on first render.
- The component suspends; the nearest
<Suspense>shows its fallback. - When the module resolves, React renders its default export.
- 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.lazy | next/dynamic | |
|---|---|---|
Needs explicit <Suspense> | Yes | No (built in) |
| Loading component option | No | loading |
| Disable SSR | No | ssr: false |
| Named exports | Manual 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.tsx2"use client";34import { lazy, Suspense, useState } from "react";56// Default export required7const AdvancedPanel = lazy(() => import("./advanced-panel"));8// Named export wrapped into a default9const AuditLog = lazy(() => import("./audit").then((m) => ({ default: m.AuditLog })));1011export function Advanced() {12 const [open, setOpen] = useState(false);1314 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}2627// 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.