Error handling in React best practices

React 16 introduces a new concept called “error boundary” to handle errors occur inside React components without breaking the whole app.

Error boundaries are React components that catch JavaScript errors
anywhere in their child component tree, log those errors, and display
a fallback UI
instead of the component tree that crashed.

Error Boundary components have been made possible with a new life cycle method componentDidCatch(error, info). Not like other life cycle methods, this will get called only if any error occurred in during rendering, in lifecycle methods, or constructors of any child (including all grandchildren) component of the component.

In code, Error Boundary component will be something like follows.

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

  componentDidCatch(error, info) {
    // Display fallback UI
    this.setState({ hasError: true });
  }

  render() {
    if (this.state.hasError) {
      // You can render any custom fallback UI
      return <h1>Error occurred!</h1>;
    }
    return this.props.children;
  }
}

We can use this Error Boundary component as a normal component in our code.

<ErrorBoundary>
  <MyComponent />
</ErrorBoundary>

Now if MyComponent throws any JavaScript error in during rendering, in lifecycle method, or in constructing, componentDidCatch of Error Boundary component will trigger and change the state to show Error occurred! message instead of the broken MyComponent.

This new functionality comes with another vital implication that you wanted to know before migrating to React 16. Previously, if an error occurs, it leaves corrupted UI even though it doesn’t usually work as expected until you reload the page. However, in React 16, if an error hasn’t handled by any error boundary, it will result in unmounting of the whole app.

Because of this, you are adding error boundaries to your app appropriately will give a better experience to your user. So users will be able to interact with a part of your app even though some areas of UI have crashed.

Refer React official documentation on error boundaries or this official blog post for more information. They cover almost everything you need to know about this new feature.

Leave a Comment