What are Error Boundaries?
Error boundaries are components that catch JavaScript errors thrown while rendering their children, in lifecycle methods and in constructors, log them, and display a fallback UI instead of unmounting the whole app. They are still written as class components (using static getDerivedStateFromError and componentDidCatch) or via a library such as react-error-boundary.
What they catch
- Errors during rendering of any descendant.
- Errors thrown by Suspense data sources (
use(promise)rejections,useSuspenseQuery). - Errors from React 19 Actions (async transitions, form actions) bubble to the nearest boundary.
What they do not catch
- Errors in event handlers (use
try/catch). - Errors in async code outside React's rendering (timers, plain promises).
- Errors during server rendering (handled by the SSR APIs or framework).
- Errors thrown in the boundary itself.
Placement
- A top-level boundary for a friendly "something went wrong" page.
- Granular boundaries around widgets, routes and third-party components, so one failure does not take down the page.
- Reset with
resetKeys(for example when the route changes) or a retry button.
Reporting (React 19)
createRoot(el, { onCaughtError, onUncaughtError, onRecoverableError }) centralizes reporting to monitoring tools; React 19 also stopped re-throwing caught errors, reducing duplicate console noise.
Framework helpers
- React Router: route
ErrorBoundaryexports. - Next.js:
error.tsx,global-error.tsxandcatchErrorfromnext/error.
Why there is no hook
componentDidCatch has no hook equivalent yet, so libraries wrap a class for you.
Code example
1import { ErrorBoundary, type FallbackProps } from "react-error-boundary";2import { createRoot } from "react-dom/client";34function Fallback({ error, resetErrorBoundary }: FallbackProps) {5 return (6 <div role="alert">7 <p>Something went wrong: {error instanceof Error ? error.message : "Unknown error"}</p>8 <button onClick={resetErrorBoundary}>Try again</button>9 </div>10 );11}1213function RevenueChart({ data }: { data: number[] | null }) {14 if (!data) throw new Error("No revenue data"); // caught by the boundary below15 return <p>{data.length} points</p>;16}1718export function Dashboard({ data, route }: { data: number[] | null; route: string }) {19 return (20 <main>21 <h1>Dashboard</h1> {/* stays visible if the chart fails */}22 <ErrorBoundary FallbackComponent={Fallback} resetKeys={[route]} onError={(e) => console.error("chart failed", e)}>23 <RevenueChart data={data} />24 </ErrorBoundary>25 </main>26 );27}2829createRoot(document.getElementById("root")!, {30 onCaughtError: (error, info) => console.error("caught", error, info.componentStack), // send to monitoring31 onUncaughtError: (error) => console.error("uncaught", error),32}).render(<Dashboard data={null} route="/" />);
Practice this question
Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the React set.