Error Boundary

  • error boundary is a component using one or both of the following methods:
    • static getDerivedStateFromError
    • componentDidCatch
  • Whenever error happens while rendering <CounterComponent />, it will fallback to default UI defined by <ErrorBoundary>
<ErrorBoundary>
  <CounterComponent/>
</ErrorBoundary>
class ErrorBoundary extends React.Component {
  constructor(props) {
    super(props);
    this.state = { hasError: false };
  }
  static getDerivedStateFromError(error) {
    return { hasError: true };
  }
  componentDidCatch(error, errorInfo) {
    logErrorToMyService(error, errorInfo);
  }
  render() {
    if (this.state.hasError) {
      return <h4>Something went wrong</h4>;
    }
    return this.props.children;
  }
}