Styling and UI Patterns · Lesson 26 of 31
Error Boundaries in React
If a component throws an error while rendering, React unmounts the whole app – users see a blank page. An error boundary is a component that catches errors in the tree below it and shows a fallback instead, so one broken widget doesn't take down the page.
In this lesson
- What happens without a boundary
- Writing an error boundary (a class component)
- The react-error-boundary package with retry
- What boundaries don't catch
Writing an error boundary
Error boundaries are the one thing that still needs a class component: React uses two lifecycle methods to catch errors.
import { Component, useState } from "react";
class ErrorBoundary extends Component {
state = { error: null };
static getDerivedStateFromError(error) { // render the fallback next time
return { error };
}
componentDidCatch(error, info) { // log it (e.g. to Sentry)
console.log("reported:", error.message);
}
render() {
if (this.state.error) return this.props.fallback;
return this.props.children;
}
}
function PriceWidget({ price }) {
return <p>Price: ₹{price.toFixed(2)}</p>; // crashes if price is undefined
}
export default function App() {
const [broken, setBroken] = useState(false);
return (
<div>
<h1>Course page</h1>
<button onClick={() => setBroken(true)}>Load bad data</button>
<ErrorBoundary fallback={<p role="alert">⚠ Couldn't show the price.</p>}>
<PriceWidget price={broken ? undefined : 499} />
</ErrorBoundary>
<p>Lessons: 31</p>
</div>
);
}
Course page [Load bad data] Price: ₹499.00 Lessons: 31 › click “Load bad data” Course page [Load bad data] ⚠ Couldn't show the price. Lessons: 31 console: reported: Cannot read properties of undefined (reading 'toFixed')
The heading, button and lesson count stay on screen; only the broken widget is replaced. (In development, React also prints the caught error and the component stack to the browser console.)
react-error-boundary
In practice most teams use the small react-error-boundary package (npm i react-error-boundary). It adds a fallback component with a reset function, so users can try again:
import { useState } from "react";
import { ErrorBoundary } from "react-error-boundary";
let serviceUp = false; // the service is down at first
function Recommendations() {
if (!serviceUp) throw new Error("Recommendation service timed out");
return <ul><li>Next.js</li><li>TypeScript</li></ul>;
}
function Fallback({ error, resetErrorBoundary }) {
return (
<div role="alert">
<p>Something went wrong: {error.message}</p>
<button onClick={resetErrorBoundary}>Try again</button>
</div>
);
}
export default function App() {
const [userId] = useState(7);
return (
<ErrorBoundary
FallbackComponent={Fallback}
onError={(error) => console.log("logged:", error.message)}
onReset={() => { serviceUp = true; }} // e.g. clear a cache before retrying
resetKeys={[userId]} // also reset automatically when these change
>
<h2>Recommended for you</h2>
<Recommendations />
</ErrorBoundary>
);
}
Something went wrong: Recommendation service timed out [Try again] console: logged: Recommendation service timed out › click “Try again” Recommended for you • Next.js • TypeScript
Where to put boundaries
Layered boundaries
- App-level boundary – "Something went wrong, reload" page; last resort
- Route-level boundary – keeps the header and navigation working (React Router's errorElement, Next.js error.js)
- Widget boundaries – around independent parts: comments, charts, ads, recommendations
- Route-level boundary – keeps the header and navigation working (React Router's errorElement, Next.js error.js)
What error boundaries don't catch
| Error in… | Caught? | Handle it with |
|---|---|---|
| rendering, or a lazy/Suspense load | yes | the boundary |
| event handlers (onClick) | no | try/catch and state |
| async code (setTimeout, fetch, promises) | no | try/catch / .catch, then set an error state |
| the boundary component itself | no | a boundary higher up |
import { useState } from "react";
export default function App() {
const [error, setError] = useState(null);
async function handleDownload() {
try {
throw new Error("Certificate not ready yet"); // e.g. a failed fetch
} catch (err) {
setError(err.message); // handlers manage their own errors
}
}
return (
<div>
<button onClick={handleDownload}>Download certificate</button>
{error && <p role="alert">{error}</p>}
</div>
);
}
[Download certificate] › click “Download certificate” [Download certificate] Certificate not ready yet
To send an async error to the nearest boundary anyway, react-error-boundary provides useErrorBoundary().showBoundary(error).
Practice
Try it yourself
Wrap two independent widgets in separate boundaries so that one crashing doesn't hide the other.
Show solution
import { ErrorBoundary } from "react-error-boundary"; function Weather() { throw new Error("Weather API down"); } function Streak() { return <p>🔥 15-day streak</p>; } export default function App() { return ( <> <ErrorBoundary fallback={<p>Weather unavailable</p>}> <Weather /> </ErrorBoundary> <ErrorBoundary fallback={<p>Streak unavailable</p>}> <Streak /> </ErrorBoundary> </> ); }Weather unavailable 🔥 15-day streak
Quick check
What happens to the app when a render error isn't caught?
React unmounts the whole tree – a blank page.
Which two methods make a class an error boundary?
static getDerivedStateFromError (to show the fallback) and componentDidCatch (to log).
Does an error boundary catch an error thrown in onClick?
No – use try/catch in the handler.
Summary
- Error boundaries catch render errors below them and show a fallback.
- Use react-error-boundary for fallbacks with reset and logging; layer boundaries by app, route and widget.
- Handle errors in event handlers and async code yourself.
Finished this lesson?
Mark it complete to track your progress, then carry on with the next lesson.