ReactMedium

Error Boundary implementation

An error boundary is a class component that implements static getDerivedStateFromError(error) to switch to fallback UI and componentDidCatch(error, info) to log the error with its component stack. It renders children normally and the fallback after an error, and should offer a way to reset (a retry button or reset keys that change on navigation).

Implementation steps

  1. State: { error: Error | null }.
  2. static getDerivedStateFromError(error) returns { error } during render.
  3. componentDidCatch(error, info) reports to monitoring with info.componentStack.
  4. render() returns the fallback when error is set, otherwise children.
  5. reset() clears the error so children render again.
  6. componentDidUpdate resets when resetKeys change (for example the route or the selected item).

Usage guidelines

  • Wrap the app root, each route, and risky widgets separately.
  • Fallbacks should explain the problem and offer an action.
  • Errors in event handlers and async code outside rendering are not caught; handle them with try/catch or send them to state and throw during render.
  • With Suspense data (use, useSuspenseQuery) and React 19 Actions, rejected promises reach the boundary.

React 19 notes

  • Root options onCaughtError and onUncaughtError centralize reporting.
  • Caught errors are no longer re-thrown, reducing duplicate console noise.

Library alternative

react-error-boundary provides <ErrorBoundary>, FallbackComponent, resetKeys, onReset and a useErrorBoundary() hook to trigger the boundary from event handlers.

Code example

tsx
1import { Component, type ErrorInfo, type ReactNode } from "react";
2
3type Props = { children: ReactNode; fallback?: (error: Error, reset: () => void) => ReactNode; resetKeys?: unknown[] };
4type State = { error: Error | null };
5
6export class ErrorBoundary extends Component<Props, State> {
7 state: State = { error: null };
8
9 static getDerivedStateFromError(error: Error): State {
10 return { error }; // switch to fallback on the next render
11 }
12
13 componentDidCatch(error: Error, info: ErrorInfo) {
14 // Send to Sentry, Datadog, etc.
15 console.error("Boundary caught:", error, info.componentStack);
16 }
17
18 componentDidUpdate(prev: Props) {
19 const changed = (this.props.resetKeys ?? []).some((k, i) => !Object.is(k, prev.resetKeys?.[i]));
20 if (this.state.error && changed) this.reset(); // e.g. user navigated elsewhere
21 }
22
23 reset = () => this.setState({ error: null });
24
25 render() {
26 if (this.state.error) {
27 return this.props.fallback?.(this.state.error, this.reset) ?? (
28 <div role="alert">
29 <p>Something went wrong.</p>
30 <button onClick={this.reset}>Try again</button>
31 </div>
32 );
33 }
34 return this.props.children;
35 }
36}
37
38// <ErrorBoundary resetKeys={[location.pathname]} fallback={(e, reset) => <p>{e.message} <button onClick={reset}>Retry</button></p>}>
39// <Dashboard />
40// </ErrorBoundary>

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.

Open in study app