wasAsked.

Write React code to handle Error Boundaries.

Altimetrik · Role not specified · technical

Published

Asked in 2026 · React

Community answers

Posted by wasAsked editorial collection

React error boundaries are still class components (there is no hook equivalent yet), because they rely on getDerivedStateFromError and componentDidCatch. import { Component, ErrorInfo, ReactNode } from 'react'; type Props = { fallback?: ReactNode; children: ReactNode; onReset?: () => void }; type State = { hasError: boolean; error: Error | null }; export class ErrorBoundary extends Component<Props, State> { state: State = { hasError: false, error: null }; static getDerivedStateFromError(error: Error): State { return { hasError: true, error }; // switch to fallback UI on next render } componentDidCatch(error: Error, info: ErrorInfo) { // Report to monitoring (Sentry, Application Insights, etc.) console.error('UI error', error, info.componentStack); } private reset = () => { this.setState({ hasError: false, error: null }); this.props.onReset?.(); }; render() { if (this.state.hasError) { return this.props.fallback ?? ( <div role="alert"> <h2>Something went wrong.</h2> <button onClick={this.reset}>Try again</button> </div> ); } return this.props.children; } } Usage — wrap independent areas so one failure does not blank the whole page: <ErrorBoundary fallback={<p>Could not load the dashboard widget.</p>}> <SalesChart /> </ErrorBoundary> <ErrorBoundary> <Routes>...</Routes> </ErrorBoundary> What error boundaries catch - Errors thrown during rendering, in lifecycle methods and in constructors of child components. What they do not catch - Errors in event handlers (use try/catch there). - Asynchronous code (setTimeout, promises, fetch callbacks). - Errors in the boundary itself. - Server-side rendering errors. To send an async error to a boundary, store it in state and throw it during render: const [error, setError] = useState<Error | null>(null); if (error) throw error; // in an async handler: catch (e) { setError(e as Error); } The react-error-boundary library provides a ready-made <ErrorBoundary> with FallbackComponent, resetKeys (reset automatically when inputs change) and a useErrorBoundary hook (showBoundary) for async errors. Data libraries such as TanStack Query can also throw errors to boundaries (throwOnError). React 19 also adds root-level onCaughtError and onUncaughtError callbacks in createRoot for centralised error reporting.

Ravindra Wadile · · 0 likes

Sign in to add your answer

Related interview topics