Quality and Performance

Error Boundaries in React

Catch UI rendering errors and show fallback screens to improve production reliability.

What error boundaries catch

Error boundaries catch errors during:

  • Rendering
  • Lifecycle methods
  • Constructors in child components

They do not catch errors in event handlers or async callbacks.

Class-based boundary example

tsx
class ErrorBoundary extends React.Component<
  { children: React.ReactNode },
  { hasError: boolean }
> {
  state = { hasError: false };

  static getDerivedStateFromError() {
    return { hasError: true };
  }

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

Best practices

  • Wrap route-level and high-risk feature areas
  • Log errors to monitoring tools (Sentry, Datadog)
  • Provide retry or safe-navigation options in fallback UI

Next, we will cover accessibility fundamentals.