Error Boundaries

An Error Boundary is a React component that catches JavaScript errors anywhere in its child component tree, logs those errors, and displays a fallback UI instead of the component tree that crashed.

Why do we need them?

In the past, JavaScript errors inside components would corrupt React’s internal state and cause it to emit cryptic errors on next renders. These errors were always caused by an earlier error in the application code, but React did not provide a way to handle them gracefully in components, and could not recover from them.

Creating an Error Boundary

A class component becomes an error boundary if it defines either (or both) of the lifecycle methods static getDerivedStateFromError() or componentDidCatch().

JavaScript

import React from 'react';

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

  static getDerivedStateFromError(error) {
    // Update state so the next render will show the fallback UI.
    return { hasError: true };
  }

  componentDidCatch(error, errorInfo) {
    // You can also log the error to an error reporting service
    console.error("Caught by ErrorBoundary:", error, errorInfo);
  }

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

    return this.props.children; 
  }
}

export default ErrorBoundary;          

How to use it

You can use it as a regular component to wrap any part of your app that might fail.

JavaScript

<ErrorBoundary>
  <MyVeryRiskyComponent />
</ErrorBoundary>          

Where to place Error Boundaries?

Note: Error boundaries do **not** catch errors for: Event handlers, Asynchronous code (e.g. setTimeout), Server-side rendering, or Errors thrown in the error boundary itself.