JS Guide
HomeQuestionsTopicsCompaniesResources
BookmarksSearch

Built for developers preparing for JavaScript, React & TypeScript interviews.

ResourcesQuestionsSupport
HomeQuestionsSearchProgress
HomeQuestionsreact
PrevNext

Learn the concept

Error Boundaries

react
senior
error-handling

How do Error Boundaries work in React and what are their limitations?

error-boundaries
error-handling
try-catch
componentDidCatch
fallback
Quick Answer

Error Boundaries are class components that catch JavaScript errors in their child component tree, log them, and display fallback UI. They don't catch errors in event handlers, async code, SSR, or errors thrown in the boundary itself.

Detailed Explanation

What Error Boundaries Do:

  • Catch errors during rendering, lifecycle, constructors
  • Prevent entire app from crashing
  • Display fallback UI for broken part
  • Log errors for debugging

Limitations (don't catch):

  • Event handlers (use try/catch)
  • Async code (promises, setTimeout)
  • Server-side rendering
  • Errors in the error boundary itself

Implementation:

  • Must be class component natively (use react-error-boundary library for a hook-based API via useErrorBoundary)
  • Implement static getDerivedStateFromError() for fallback UI
  • Implement componentDidCatch() for logging

Best Practices:

  • Place at strategic points (routes, features)
  • Different granularity for different errors
  • Provide recovery mechanisms
  • Log to error monitoring service

React 19 Error Handling Updates:

  • react-error-boundary library provides ErrorBoundary component with hooks API (useErrorBoundary, showBoundary)
  • When use(promise) rejects, the error propagates to the nearest error boundary
  • Server Component errors are serialized and sent to the client — the error boundary catches them client-side
  • Error boundaries in RSC contexts may receive sanitized error messages (details stripped for security)

Code Examples

Basic Error BoundaryJSX
class ErrorBoundary extends React.Component {
  constructor(props) {
    super(props);
    this.state = { hasError: false, error: null };
  }
  
  // Update state to show fallback UI
  static getDerivedStateFromError(error) {
    return { hasError: true, error };
  }
  
  // Log error information
  componentDidCatch(error, errorInfo) {
    console.error('Error caught:', error);
    console.error('Component stack:', errorInfo.componentStack);
    
    // Send to error monitoring service
    logErrorToService(error, errorInfo);
  }
  
  render() {
    if (this.state.hasError) {
      return this.props.fallback || (
        <div className="error-fallback">
          <h2>Something went wrong</h2>
          <button onClick={() => this.setState({ hasError: false })}>
            Try again
          </button>
        </div>
      );
    }
    
    return this.props.children;
  }
}

// Usage
function App() {
  return (
    <ErrorBoundary fallback={<ErrorPage />}>
      <MainContent />
    </ErrorBoundary>
  );
}

Real-World Applications

Use Cases

Graceful Degradation

Wrapping feature sections with error boundaries so one failing widget doesn't crash the entire dashboard

Error Reporting Integration

Connecting error boundaries to Sentry/DataDog for automatic error capture with React component context

Retry Mechanisms

Implementing try again buttons in error boundary fallbacks for transient failures

Mini Projects

Error Boundary Hierarchy

intermediate

Build an app with nested error boundaries at route, feature, and component levels with different fallback UIs

Error Recovery System

advanced

Implement an error boundary system with automatic retry, error classification, and user-friendly recovery options

Industry Examples

Sentry

Provides React-specific error boundary integration for error monitoring

react-error-boundary

Community standard library providing hook-based error boundary API

Resources

React Docs - Catching rendering errors with an error boundary

docs

react-error-boundary package

docs

Related Questions

What are React's concurrent features and how do Suspense and transitions work?

senior
concurrent
Previous
What are React's concurrent features and how do Suspense and transitions work?
Next
Explain common React patterns: Compound Components, Render Props, and Custom Hooks.
PrevNext