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

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.