Suspense Boundary for Lazy Components
What you'll learn: Why every React.lazy() component must be wrapped in a <Suspense> boundary and how React handles the loading state.
The Missing Piece of Lazy Loading
You've learned that React.lazy() enables code splitting by loading components on demand. But here's the catch: lazy components throw a promise while loading. Without something to catch that promise, your app would crash.
That "something" is the <Suspense> boundary.
How It Works
When React tries to render a lazy component that hasn't loaded yet:
- The lazy component throws a promise (yes, literally throws!)
- React catches that thrown promise at the nearest
<Suspense>boundary - React renders the
fallbackUI you specified - When the promise resolves, React retries rendering the actual component
import { Suspense, lazy } from 'react';
const Dashboard = lazy(() => import('./Dashboard'));
function App() {
return (
<Suspense fallback={<div>Loading dashboard...</div>}>
<Dashboard />
</Suspense>
);
}
The Analogy
Think of <Suspense> as a safety net under a trapeze artist (your lazy component). When the component "jumps" (starts loading), it temporarily falls. The safety net catches it and displays a "performance in progress" sign (fallback). Once the component "lands safely" (finishes loading), the real show begins.
What Happens Without Suspense?
If you try to render a lazy component without a <Suspense> boundary, React will throw an error. The thrown promise has nowhere to go, and your app breaks. Always wrap lazy components in <Suspense>.
Key Takeaway: Lazy components require a <Suspense> boundary because they throw promises during loading. The boundary catches these promises and displays the fallback UI until the component is ready, preventing your app from crashing.