Explain it simply
Suspense and error boundaries in plain language
As an app grows, you do not want to ship code for parts most users never open, such as a Reports page, in the first load. lazy() says 'download this component the first time it must be shown'. While it downloads, <Suspense> shows a temporary fallback such as 'Loading…' so the screen is not blank.
An error boundary is like the fuse box in a house. When one room shorts out, only that fuse blows instead of the whole house going dark. When a component crashes while rendering, the boundary replaces that part with a message such as 'Could not load reports.' and the rest of the app keeps working.
Problem → Why → Solution
The problem: one widget's bug blanks the whole screen
A dashboard has ten widgets, and PriceWidget receives unexpected data from an API and throws while rendering. Without an error boundary, React unmounts the entire root and the user sees a blank white screen, losing the nine widgets that were fine. Meanwhile, the Reports page's big chart library downloads as soon as the home page opens, slowing down the first load.
import Reports from './Reports.jsx'; // big chart code, loaded up front
function PriceWidget({ price }) {
if (price < 0) throw new Error('price cannot be negative');
return <p>Price: {price} USD</p>;
}
export default function Dashboard({ price }) {
return (
<>
<PriceWidget price={price} /> {/* one throw -> the whole app unmounts */}
<Reports />
</>
);
}Why the whole app disappears
When an error happens during rendering, React decides the UI is no longer safe to show. If no error boundary catches it, React removes the entire component tree rather than display a broken UI. Error boundaries draw borders that say 'if this part breaks, show this fallback', while lazy plus Suspense makes code download only when it is needed.
Core concept: boundaries for loading and for errors
lazy(() => import('./Reports.jsx')) calls import() only when Reports must render for the first time, and bundlers such as Vite split each dynamic import into its own JavaScript file, a chunk. Until the chunk arrives, Reports suspends, which tells React it cannot finish rendering yet. React walks up the tree to the nearest <Suspense>, shows its fallback, and retries Reports once the chunk is there. Declare lazy components at the top level of a module; declared inside a component, they become a new component type on every render.
Suspense is not only for lazy code: reading a cached promise with React's use(), or data loading in frameworks and libraries that support Suspense, can suspend too. Fetching inside useEffect, however, never triggers Suspense; that loading state is yours to show with ordinary state.
An error boundary is a class component with static getDerivedStateFromError(error), componentDidCatch(error, info), or both. When a component below it throws while rendering, in a lifecycle method or in an effect, getDerivedStateFromError switches the state so the fallback renders, and componentDidCatch is the place to log the error. There is no hook version of an error boundary, so you write one class yourself or use a library such as react-error-boundary.
A boundary catches errors only from the components below it; an error inside the boundary's own render travels up to the next boundary, so keep fallback UI simple. A boundary's error state also never clears on its own: it shows its children again only after you reset that state or remount it with a new key.
| Where the error happens | Caught by a boundary? |
|---|---|
| Rendering, lifecycle methods, effects | Yes |
| A failed lazy() import | Yes |
| Event handlers such as onClick | No; use try/catch |
| setTimeout, promises outside rendering | No |
- Child suspends: nearest Suspense
- Fallback shows, then React retries
- Child throws: nearest error boundary
- Its fallback shows; the rest runs on
Where you place boundaries is a design decision: how much of the screen should show loading or error together.
General pattern
const LazyPart = lazy(() => import('./SomePart.jsx')); // module top level
class ErrorBoundary extends Component {
state = { hasError: false };
static getDerivedStateFromError() { return { hasError: true }; }
render() { return this.state.hasError ? fallbackUI : this.props.children; }
}
<ErrorBoundary>
<Suspense fallback={loadingUI}><LazyPart /></Suspense>
</ErrorBoundary>Declare the lazy component at the top of the module, put Suspense where loading should show, and wrap an error boundary around it so even a failed chunk download is caught.
Worked example: a guarded lazy Reports page
Reports is split into its own chunk, and Suspense shows a loading message while it downloads. The error boundary catches a failed chunk download, such as a dropped connection or a file removed by a new deploy, as well as a crash while Reports renders, and shows an alert message instead.
import { Component, lazy, Suspense } from 'react';
const Reports = lazy(() => import('./Reports.jsx'));
class ErrorBoundary extends Component {
state = { failed: false };
static getDerivedStateFromError() {
return { failed: true };
}
render() {
if (this.state.failed) {
return <p role="alert">Could not load reports.</p>;
}
return this.props.children;
}
}
export default function App() {
return (
<ErrorBoundary>
<Suspense fallback={<p>Loading reports…</p>}>
<Reports />
</Suspense>
</ErrorBoundary>
);
}Code breakdown
- Lazy, at module level
const Reports = lazy(() => import('./Reports.jsx'));import() runs only when Reports renders for the first time. Reports.jsx must have a default export.
- Switch to the fallback
static getDerivedStateFromError() {When something below throws, React calls this static method and merges the returned { failed: true } into state.
- Render the alert
return <p role="alert">Could not load reports.</p>;role="alert" makes screen readers announce the message right away. Without an error, this.props.children renders as usual.
- Loading boundary inside the error boundary
<Suspense fallback={<p>Loading reports…</p>}>This fallback shows while Reports is suspended. ErrorBoundary sits outside Suspense, so a failed import reaches the boundary.
First, 'Loading reports…' appears. As soon as the Reports chunk arrives, the Reports component replaces the fallback. If the chunk fails to download or Reports throws while rendering, the 'Could not load reports.' alert is shown instead.Where to place boundaries
Wrapping the whole app in one boundary turns any widget crash into a full-screen error page. Wrapping every widget separately produces a crowd of spinners popping in one by one and a jumpy screen. In practice teams choose the middle: one 'Something went wrong' boundary at the very top, one per route or page, and dedicated ones around fragile parts such as third-party widgets.
lazy remembers a failed import
lazy() caches the result of import(), including a failure. Resetting the boundary and rendering the same lazy component again does not retry the download; it fails with the same error. For chunks that vanished after a new deploy, a 'Reload page' button that calls window.location.reload() in the fallback is the simplest fix.
In real projects
Suspense and error boundaries in real projects
Production React apps almost always use these two tools together, for performance and for reliability. You cannot guarantee nothing ever crashes, but you can control what users see when something does.
- Route-based code splitting: each page is wrapped in lazy(), so the home page never downloads the admin panel's code; routes are the best place to start splitting.
- Heavy widgets: components built on large libraries such as charts, rich-text editors or maps are lazy-loaded with a skeleton UI as the fallback.
- Error monitoring: componentDidCatch sends the error and info.componentStack to a service such as Sentry, so you can trace which component crashed.
- The react-error-boundary library: instead of writing the class yourself, use a resettable boundary with props such as FallbackComponent, onReset and resetKeys.
Common mistakes
Common mistakes with Suspense and error boundaries
Expecting a boundary to catch event handler errors
An error thrown inside onClick happens outside rendering, so the boundary never sees it and no fallback appears. Catch it with try/catch in the handler and put an error message into state. The same applies to errors inside setTimeout or a fetch's .then.
Declaring lazy() inside a component
Writing function Page() { const Chart = lazy(...); ... } creates a new component type on every render, so Chart loses all its state, suspends again and flashes the fallback over and over. Declare lazy at the top level of the module.
One boundary for everything, or no way to reset
With only one boundary at the top, a small sidebar widget crash turns the whole app into an error page. A boundary's error state also never clears by itself: the fallback stays even after the data is fixed, so offer a 'Try again' button that resets the state, or change the boundary's key to start it fresh.
Mini challenge
Mini challenge: a resettable error boundary
Wrap a PriceWidget that throws on a bad price in an error boundary. The boundary shows the widget's title and the error message with a 'Try again' button, and logs the error in componentDidCatch. A 'Fix data' button outside the boundary corrects the price, and the widget comes back only after Try again.
- getDerivedStateFromError stores the error object in state
- componentDidCatch logs 'logged: <message>' to the console
- The fallback has role="alert" and shows '<title> failed: <message>' plus a Try again button
- Try again sets the error state back to null; UI outside the boundary stays visible during the crash
import { Component, useState } from 'react';
class ErrorBoundary extends Component {
// TODO: state = { error: null }
// TODO: static getDerivedStateFromError(error) -> put the error in state
// TODO: componentDidCatch(error) -> console.log a "logged: ..." line
// TODO: reset method that clears the error
render() {
// TODO: alert with "<title> failed: <message>" and a Try again button
return this.props.children;
}
}
function PriceWidget({ price }) {
// TODO: throw new Error('price cannot be negative') when price < 0
return <p>Price: {price} USD</p>;
}
export default function Dashboard() {
// TODO: price state starting at -5, a boundary around PriceWidget,
// TODO: and a "Fix data" button outside the boundary that sets the price to 25
return null;
}Expected: The first render shows the 'Price widget failed: price cannot be negative' alert with a Try again button, and the console prints 'logged: price cannot be negative'. The 'The rest of the dashboard still works.' line and the Fix data button stay visible. After Fix data the alert remains; after Try again, 'Price: 25 USD' appears.
Show hint
Writing reset = () => this.setState({ error: null }) as an arrow-function class field keeps this bound in onClick={this.reset}. It is expected that Fix data alone does not bring the widget back: the boundary's error state must be reset explicitly.
Show solution
import { Component, useState } from 'react';
class ErrorBoundary extends Component {
state = { error: null };
static getDerivedStateFromError(error) {
return { error }; // show the fallback on the next render
}
componentDidCatch(error) {
console.log(`logged: ${error.message}`); // e.g. send to a monitoring service
}
reset = () => this.setState({ error: null });
render() {
if (this.state.error) {
return (
<div role="alert">
<p>{this.props.title} failed: {this.state.error.message}</p>
<button onClick={this.reset}>Try again</button>
</div>
);
}
return this.props.children;
}
}
function PriceWidget({ price }) {
if (price < 0) throw new Error('price cannot be negative');
return <p>Price: {price} USD</p>;
}
export default function Dashboard() {
const [price, setPrice] = useState(-5);
return (
<>
<ErrorBoundary title="Price widget">
<PriceWidget price={price} />
</ErrorBoundary>
<button onClick={() => setPrice(25)}>Fix data</button>
<p>The rest of the dashboard still works.</p>
</>
);
}Quick quiz 1 / 3
Quick quiz 2 / 3
Quick quiz 3 / 3
What to remember
- lazy(() => import(...)) downloads component code the first time it is needed and belongs at module top level
- The nearest <Suspense> shows its fallback while a component suspends; fetching in useEffect never triggers it
- Error boundaries are class components (or a library such as react-error-boundary) and catch rendering, effect and lazy-import errors
- Boundaries do not catch event handler or async callback errors, so use try/catch there
- Place boundaries at the app, page and fragile-widget level, and give users a way to reset
Suspense — React