Menu

Error Boundaries and Error Handling

Error Boundaries and Error Handling

What is an Error Boundary?

If a JavaScript error is thrown while rendering, React unmounts the entire component tree — the user sees a blank white page. An error boundary catches such errors in its child tree and shows a fallback interface instead.

Error boundaries are the one remaining case where a class component is required; there is no Hook equivalent.

Example

src/components/ErrorBoundary.jsx

jsx

import { Component } from "react";

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

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

  componentDidCatch(error, info) {
    console.error("Caught by error boundary:", error, info);
  }

  render() {
    if (this.state.hasError) {
      return (
        <div className="error-fallback">
          <h2>Something went wrong.</h2>
          <button onClick={() => window.location.reload()}>Reload page</button>
        </div>
      );
    }

    return this.props.children;
  }
}

export default ErrorBoundary;

Usage

jsx

<ErrorBoundary>
  <Dashboard />
</ErrorBoundary>

How It Works

  • getDerivedStateFromError() runs when a child throws, switching the boundary into its error state.
  • componentDidCatch() is where you would log the error to a monitoring service.
  • If there is no error, the boundary simply renders its children and is invisible.

Place boundaries around independent sections so one broken widget does not take down the whole page.

What Error Boundaries Do Not Catch

Caught

Not caught

Errors during renderingErrors inside event handlers
Errors in lifecycle methodsErrors in async code (setTimeout, promises)
Errors in constructors of childrenErrors in the boundary itself

For event handlers and async code, use ordinary try / catch which is exactly what the API lessons in Module 8 did.

In practice, most teams use the react-error-boundary library rather than writing the class themselves, but understanding the mechanism matters more than the package.


ReactJS Tutorial

VA

Vishalini A



Learn via Video Course

React.js for Beginners: Build Modern Web Applications with React Logo

React.js for Beginners: Build Modern Web Applications with React

6 hrs



Get in Touch For Details