What is Error Boundary and how do you implement one?

MediumAdvanced PatternsTheory Question

Hint

Class component wrapping the tree — catches render errors and shows fallback UI instead of blank screen

Full Answer

Error Boundaries catch JavaScript errors during rendering, in lifecycle methods, and in constructors of child components. They must be class components (no hook equivalent yet).

class ErrorBoundary extends React.Component {
  constructor(props) {
    super(props);
    this.state = { hasError: false, error: null };
  }

  // Render phase — update state to show fallback
  static getDerivedStateFromError(error) {
    return { hasError: true, error };
  }

  // Commit phase — log error to monitoring service
  componentDidCatch(error, info) {
    logErrorToSentry(error, info.componentStack);
  }

  render() {
    if (this.state.hasError) {
      return this.props.fallback ?? <h2>Something went wrong.</h2>;
    }
    return this.props.children;
  }
}

// Usage — wrap features, not the entire app
function App() {
  return (
    <ErrorBoundary fallback={<ErrorPage />}>
      <ErrorBoundary fallback={<WidgetError />}>
        <SomeWidget />
      </ErrorBoundary>
      <MainContent />
    </ErrorBoundary>
  );
}

// react-error-boundary library — hook-friendly wrapper
import { ErrorBoundary } from 'react-error-boundary';

<ErrorBoundary
  FallbackComponent={ErrorFallback}
  onError={logError}
  onReset={resetApp}
>
  <App />
</ErrorBoundary>
💡 Error boundaries do NOT catch errors in event handlers, async code (setTimeout, fetch), or SSR. Use try/catch for those. Place boundaries at feature level, not component level — granular boundaries give better UX.

More Advanced Patterns Questions

Practice this in a timed sprint

5 free questions, no signup required