An error boundary isolates rendering failures in a React subtree. When a descendant throws, it replaces that subtree with fallback UI while surrounding interface—such as an application header—continues working. section 11.3
React recognizes class components implementing getDerivedStateFromError, componentDidCatch, or both. The first updates state for fallback rendering; the second can report error details to an external service. section 11.3.1
Configure boundaries around the UI whose failure should remain contained:
- Wrap routes or page content while leaving stable navigation outside the boundary. section 11.3
- Provide tailored fallback UI, such as “Something went wrong” with an instruction to reload. section 11.3.2
- Use smaller boundaries for independent widgets so one broken component does not disable usable functionality elsewhere. section 11.3.2
- Pair ErrorBoundary with Suspense: Suspense handles pending promises, while the boundary handles rendering errors or rejected loading. section 11.4 section 12.1
The react-error-boundary package provides a reusable ErrorBoundary with a FallbackComponent prop. Its fallback receives the error and can receive resetErrorBoundary, allowing a Try Again button to clear the error state. An onReset callback can restart the failed operation. section 12.1.3 section 12.1.5
Recovering from a failed message load
Place Message inside ErrorBoundary and Suspense. If Message throws while retrieving data, show an error fallback; let the user click Try Again, reset the boundary, and load the next message. section 12.1 section 12.1.5
Listing 12.4 Using the Message component
import React, {Suspense} from "react";
import {ErrorBoundary} from "react-error-boundary";
import fetchMessage from "./api";
import {makeThrower} from "./utils";
import "./styles.css";
function ErrorFallback ({error}) {
return <p className="error">{error}</p>;
}
const getMessageOrThrow = makeThrower(fetchMessage()); #1
function Message () {
const data = getMessageOrThrow(); #2
return <p className="message">{data.message}</p>; #3
}
export default function App () {
return (
<div className="App">
<ErrorBoundary FallbackComponent={ErrorFallback}> #4
<Suspense #5
fallback={<p className="loading">Loading message...</p>}
>
<Message />
</Suspense>
</ErrorBoundary>
</div>
);
}
#1 Start fetching as soon as possible.
#2 Access the data or throw an error or promise.
#3 Use the data if available.
#4 Catch thrown errors.
#5 Catch thrown promises.
Inspect the complete react-error-boundary example, including FallbackComponent, Suspense, and a throw-ready data accessor. section 12.1.3


