Sub topic 2
Showing a Fallback with Suspense
This chapter assumes you know React function components, hooks, props, ES module imports, promises, and basic bundler behavior.
Showing a fallback with Suspense
A lazy component suspends while React waits for its JavaScript chunk. Suspense is a boundary that displays its fallback during that wait.
import { lazy, Suspense } from 'react';
const Chart = lazy(() => import('./Chart'));
export default function Dashboard() {
return (
<section>
<h1>Dashboard</h1>
<Suspense fallback={<p>Loading chart...</p>}>
<Chart />
</Suspense>
</section>
);
}The fallback should explain what is loading. A small local fallback usually feels better than replacing the whole application with a blank screen.
Where to put Suspense boundaries
Place a boundary around the smallest useful part of the interface. A boundary around the entire app is simple, but it may hide already usable content. Nested boundaries let independent sections load separately.
Splitting by route
Routes are natural split points because users often visit only one page per session. Put one lazy import at each route and place Suspense above the route collection.
import { lazy, Suspense } from 'react';
import { BrowserRouter, Routes, Route } from 'react-router-dom';
const Home = lazy(() => import('./pages/Home'));
const Settings = lazy(() => import('./pages/Settings'));
export default function App() {
return (
<BrowserRouter>
<Suspense fallback={<p>Loading page...</p>}>
<Routes>
<Route path="/" element={<Home />} />
<Route path="/settings" element={<Settings />} />
</Routes>
</Suspense>
</BrowserRouter>
);
}Handling chunk load failures
A network interruption, expired deployment, or blocked request can make a dynamic import reject. An error boundary catches that error and offers a useful recovery action.
import { Component } from 'react';
export class ErrorBoundary extends Component {
state = { error: null };
static getDerivedStateFromError(error) {
return { error };
}
render() {
if (this.state.error) {
return <p>Could not load this page. Refresh and try again.</p>;
}
return this.props.children;
}
}Place ErrorBoundary outside Suspense:
<ErrorBoundary>
<Suspense fallback={<p>Loading...</p>}>
<Settings />
</Suspense>
</ErrorBoundary>Exercise
Which boundary should handle a rejected lazy import?
Show answer
An error boundary should surround the Suspense boundary, because Suspense shows waiting states but does not catch errors.