What Are Error Boundaries in React v16?

In React version 16 and above, error boundaries are a feature that allows you to catch JavaScript errors that occur during the rendering of a component tree. They are React components themselves that define a componentDidCatch(error, info) lifecycle method. When a JavaScript error is thrown within a component tree, React will walk up the tree until it finds the nearest error boundary and call its componentDidCatch method.

Error boundaries

Error boundaries are useful for preventing the entire application from crashing due to unhandled errors. Instead, they enable you to gracefully handle errors, display fallback UI, and log error information for debugging purposes.

Here's an example of an error boundary component.

import React, { Component } from 'react';

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

  componentDidCatch(error, errorInfo) {
    // Catch errors in any components below and re-render with error message
    this.setState({
      hasError: true,
      error: error,
      errorInfo: errorInfo
    });
    // Log the error to an error reporting service
    // logErrorToMyService(error, errorInfo);
  }

  render() {
    if (this.state.hasError) {
      // Fallback UI when an error occurs
      return (
        <div>
          <h2>Something went wrong.</h2>
          <details style={{ whiteSpace: 'pre-wrap' }}>
            {this.state.error && this.state.error.toString()}
            <br />
            {this.state.errorInfo.componentStack}
          </details>
        </div>
      );
    }
    // Render children if there's no error
    return this.props.children;
  }
}

export default ErrorBoundary;

In this example

  • ErrorBoundary is a React component that defines a componentDidCatch(error, errorInfo) method.
  • When an error occurs within its child components, React will call componentDidCatch, allowing the error boundary to handle the error.
  • Inside componentDidCatch, you can set the state to indicate that an error has occurred and store the error and error information.
  • In the render method, if an error has occurred (hasError is true), the error boundary renders a fallback UI.
  • The error information, such as the error message and stack trace, can be displayed to the user or logged to an error reporting service for debugging purposes.
  • If no error occurs, the error boundary simply renders its child components.

To use the error boundary component, wrap it around the components that you want to catch errors.

<ErrorBoundary>
  <MyComponent />
</ErrorBoundary>

By wrapping components with error boundaries strategically, you can prevent crashes and ensure a better user experience by providing informative error messages or fallback UIs.