JS Guide
HomeQuestionsSearchResources
Search

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

ResourcesQuestionsSupport
HomeQuestionsSearchProgress
HomeQuestionsreact
PrevNext
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 (no hooks equivalent)
  • 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

Code Examples

Basic Error Boundary
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>
  );
}

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.