Lesson 39 +10 XP

Error Boundaries

Error Boundaries

JavaScript errors inside component render methods or lifecycle hooks used to unmount the entire React application tree, displaying a blank white screen to users. Error Boundaries catch JavaScript errors in child components and display a fallback UI instead of crashing the app.

What is an Error Boundary?

An Error Boundary is a class component that defines either (or both) of the following lifecycle methods:

  • static getDerivedStateFromError(error): Updates state to trigger a fallback UI render after an error is thrown.
  • componentDidCatch(error, errorInfo): Logs error details to error reporting services (Sentry, LogRocket).
import React from 'react';

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

  static getDerivedStateFromError(error) {
    // Update state so the next render shows fallback UI
    return { hasError: true, errorMessage: error.message };
  }

  componentDidCatch(error, errorInfo) {
    // Log error details to analytics service
    console.error("ErrorBoundary caught an error:", error, errorInfo);
  }

  render() {
    if (this.state.hasError) {
      return (
        <div className="error-fallback">
          <h2>Oops! Something went wrong.</h2>
          <p>{this.state.errorMessage}</p>
          <button onClick={() => this.setState({ hasError: false })}>Try Again</button>
        </div>
      );
    }

    return this.props.children;
  }
}

Using Error Boundaries in Your App

Wrap potentially unstable components inside your Error Boundary.

function App() {
  return (
    <div className="app">
      <Header />
      <ErrorBoundary>
        <WidgetThatMightCrash />
      </ErrorBoundary>
      <Footer />
    </div>
  );
}

If <WidgetThatMightCrash /> throws an error, the ErrorBoundary displays the fallback UI only for that widget area, while <Header /> and <Footer /> remain fully functional!

What Error Boundaries Do NOT Catch

⚠️ DocHero Safety Disclaimer

Error boundaries do NOT catch errors inside: 1. Event handlers (onClick={() => throw Error()} -> use standard try/catch). 2. Asynchronous code (setTimeout or fetch callbacks). 3. Server-side rendering (SSR). 4. Errors thrown in the Error Boundary itself.

Summary & TL;DR

  • Error Boundaries catch runtime rendering errors in child components and display fallback UI instead of a blank screen.
  • Implemented as class components defining getDerivedStateFromError or componentDidCatch.
  • Protects the rest of the application tree from crashing when one component fails.