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
- State:
{ error: Error | null }. static getDerivedStateFromError(error)returns{ error }during render.componentDidCatch(error, info)reports to monitoring withinfo.componentStack.render()returns the fallback whenerroris set, otherwisechildren.reset()clears the error so children render again.componentDidUpdateresets whenresetKeyschange (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/catchor 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
onCaughtErrorandonUncaughtErrorcentralize 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";23type Props = { children: ReactNode; fallback?: (error: Error, reset: () => void) => ReactNode; resetKeys?: unknown[] };4type State = { error: Error | null };56export class ErrorBoundary extends Component<Props, State> {7 state: State = { error: null };89 static getDerivedStateFromError(error: Error): State {10 return { error }; // switch to fallback on the next render11 }1213 componentDidCatch(error: Error, info: ErrorInfo) {14 // Send to Sentry, Datadog, etc.15 console.error("Boundary caught:", error, info.componentStack);16 }1718 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 elsewhere21 }2223 reset = () => this.setState({ error: null });2425 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}3738// <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.