ReactEasy

What is React.lazy?

lazy(load) defines a component whose code is loaded the first time it renders. load is a function returning a promise for a module with a default export, typically () => import("./Chart"). While loading, the component suspends, so it must be rendered inside a <Suspense> boundary.

Rules

  • Call lazy at module level, not inside a component, or the component is re-created and its state reset on every render.
  • The module must default-export a component. For named exports: lazy(() => import("./charts").then((m) => ({ default: m.BarChart }))).
  • Wrap with <Suspense fallback> somewhere above it.
  • The load function runs once; the result is cached.

Preloading

Call the same import() early (on hover, on idle, or when a route loader starts) so the chunk is ready before render.

Error handling

Network failures reject the promise and throw during render. Use an error boundary with a "Retry" or "Reload" button; a common cause is stale chunks after a deployment.

Server rendering

lazy works with streaming SSR in React 18+: the server waits for or streams the component. Frameworks like Next.js offer next/dynamic with extra options such as ssr: false.

Typical uses

Route components, modals, charts, editors and admin-only features.

Code example

tsx
1import { lazy, Suspense, useState } from "react";
2import { ErrorBoundary } from "react-error-boundary";
3
4const loadSettings = () => import("./settings-panel");
5const SettingsPanel = lazy(loadSettings);
6
7const BarChart = lazy(() => import("./charts").then((m) => ({ default: m.BarChart }))); // named export
8
9export function App() {
10 const [open, setOpen] = useState(false);
11
12 return (
13 <div>
14 <button onMouseEnter={loadSettings} onClick={() => setOpen(true)}>Settings</button>
15
16 <ErrorBoundary fallbackRender={({ resetErrorBoundary }) => (
17 <p>Could not load. <button onClick={resetErrorBoundary}>Retry</button></p>
18 )}>
19 <Suspense fallback={<p>Loading…</p>}>
20 {open && <SettingsPanel />}
21 <BarChart data={[3, 5, 2]} />
22 </Suspense>
23 </ErrorBoundary>
24 </div>
25 );
26}

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 React set.

Open in study app