liveBook · Manning

Lazy

As explained in React Hooks in Action: With Suspense and Concurrent Mode

lazy is a React API for defining a component whose code is loaded on demand.

React.lazy defines a component whose module loads only when React first renders it. Pair it with Suspense so users see fallback UI instead of a stalled interface. section 11.0 section 11.4

Use lazy components by following these rules:

  • Pass lazy a function that returns the promise from a dynamic import. section 11.2.1
  • Resolve the promise to a module whose default export is the component. section 11.2.1
  • Place the rendered lazy component below a Suspense boundary with suitable fallback content. section 11.2.3
  • Use an error boundary for rejected loading promises or errors raised while rendering. section 11.2.3

Load a calendar after user interaction

const LazyCalendar = lazy(() => import("./Calendar.js"));\n\nfunction CalendarWrapper() {\n const [isOn, setIsOn] = useState(false);\n return isOn ? (\n <LazyCalendar />\n ) : (\n <button onClick={() => setIsOn(true)}>Show Calendar</button>\n );\n}\n\nA route-level version lazily imports BookingsPage, BookablesPage, and UsersPage, while a shared Suspense boundary renders a PageSpinner during loading. section 11.2.4

Table 11.1 The steps React takes when it encounters a lazy component (view table figure)

If the LazyComponent object contains

Actions

A component

Call the component.

An unresolved promise

Throw the promise.

A function that returns a promise

Call the function to get the promise.

Store the promise in the LazyComponent object.

Call the promise’s then method so that when the promise resolves, the component is stored in the LazyComponent object.

Throw the promise.

Trace how React handles a lazy component containing a component, an unresolved promise, or a promise-returning loader. section 11.2.3

How React Hooks in Action: With Suspense and Concurrent Mode covers it

How deep it goes
Explains promise loading, default exports, internal lazy states, and Suspense handoff, but defers rejected-load handling to error boundaries.
Examples
Demonstrates a delayed calendar, button-triggered rendering, route-level page splitting, and nested Bookables components.
What it assumes
Assumes familiarity with React components, JSX, imports, promises, and rendering, while defining the lazy module contract explicitly.
What you can do after
Apply it via React.lazy and dynamic import to reduce initial bundles and provide loading and error fallbacks.
How it connects
Connects dynamic import, code splitting, Suspense, fallback UI, routes, and error boundaries.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of React Hooks in Action: With Suspense and Concurrent Mode. The section links point to the parts of the book it draws on.