Show a loading fallback with Suspense
19.3
Wrap a lazily loaded part of the screen so visitors see a loading message while its code arrives.
On this page
Load a component on demand
Declare lazy outside the component. The import should resolve to a module with the component as its default export. Suspense shows its fallback while the code loads. A rejected import can be handled by an error boundary around Suspense.
import React, { lazy, Suspense } from "react";
import SectionBoundary from "./SectionBoundary.jsx";
const StockChart = lazy(() => import("./StockChart.jsx"));
export default function Reports() {
return (
<SectionBoundary>
<Suspense fallback={<p role="status">Loading chart…</p>}>
<StockChart />
</Suspense>
</SectionBoundary>
);
}
Choose which part should wait
Put the boundary close to the slow part so the page navigation and headings can stay visible. Suspense works with lazy and supported data sources. For fetch calls started in an effect, keep using an explicit loading and error state.
import { lazy, Suspense } from "react";
const ProductReviews = lazy(() => import("./ProductReviews.jsx"));
export default function ProductPage() {
return (
<main>
<h1>Notebook</h1>
<p>Available in three colors.</p>
<Suspense fallback={<p>Loading reviews…</p>}>
<ProductReviews />
</Suspense>
</main>
);
}