[]previous and next page

lazy

Defines a component whose code is loaded on first render.

Defines a component whose code is loaded on first render. While loading, the nearest <Suspense> shows its fallback; a failed load throws to the nearest <ErrorBoundary> and the next render retries.

Import#

ts
import { lazy } from "@shadow-js/web";

Signature#

ts
function lazy<P>(
  loader: () => Promise<{ default: ComponentFunction<P> }>,
): LazyComponent<P>

Parameters#

Name Description
loader Returns a promise of a module whose default export is the component, such as () => import("./chart"). Called at most once while its load succeeds.

Returns#

A LazyComponent.

Throws#

  • Nothing synchronously. A rejected load surfaces as an error when the component's output is read, so the nearest <ErrorBoundary> takes it; preload() rejects with the same error.

Examples#

ts
import { lazy, Suspense } from "@shadow-js/web";

function Chart(props: { title: string }) {
  return <h2>{props.title}</h2>;
}

// In an app the loader is `() => import("./chart")`.
const LazyChart = lazy(() => Promise.resolve({ default: Chart }));

function Page() {
  return (
    <Suspense fallback={<p>Loading...</p>}>
      <LazyChart title="Sales" />
    </Suspense>
  );
}