In this tutorial, we will handle Component Error in React using Error Boundaries. Before React 16, errors emitted from a component’s rendering proved hard to handle.
This caused cryptic errors in the console as well as unexpected behaviors in the user’s experience. These kinds of render-based errors cannot be caught since React components are declarative. Hence, you can’t just throw in a try…catch block inside a component.

Error Boundaries

Errors are good things, they are feedback we get from malfunctions or bad inputs from users. They shouldn’t be ignored even when they don’t have immediate side effects. Side effects may also occur in another render phase, and when it does it becomes increasingly hard to deal with.

React 16 introduced a component called Error Boundaries to help handle component-based errors. Basically, you wrap a component that might emit errors with an Error Boundary and the Error Boundary component catches the error once that happens.

React Error Boundary wraps component diagram

Another lifecycle method

What makes a component an Error Boundary is a lifecycle method called componentDidCatch. When a component implements this method it automatically becomes an Error Boundary and can handle errors emitted in a child’s render().

Here is the signature for componentDidCatch:

    componentDidCatch(error, errorInfo)

The method has two arguments:

  • error: the actual error message that tells you what went wrong
  • errorInfo: additional details about the error including the stack trace to help you debug the error.

A buggy component

componentDidCatch catches errors in render) and other lifecycle methods. Here is an example of a component that has a catchable error:

    class Buggy extends React.Component {
      state = { greeting: "Welcome"};
      componentDidMount() {
        throw new Error("An error has occured in Buggy component!");
      }
      render() {
        return <h2>{this.state.greeting}</h2>;
      }
    }

This component keeps throwing the error in the componentDidMount lifecycle method. It’s not a real use-case example but enough to show a component that has errors with rendering.

When you try rendering this component, nothing happens and the user gets no feedback on what is going on:

    const App = () => (
      <div style={styles}>
        <h2>Error Boundaries Example</h2>
        <Buggy />
      </div>
    );

    ReactDOM.render(<App />, document.getElementById("root"));

The demo below shows that nothing renders because of the error:

Wrapping with an Error Boundary

Let’s add the following component to the app:

    class ErrorBoundary extends React.Component {
      state = { error: null, errorInfo: null };

      componentDidCatch(error, errorInfo) {
        this.setState({
          error: error,
          errorInfo: errorInfo
        });
      }

      render() {
        if (this.state.errorInfo) {
          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>
          );
        }

        return this.props.children;
      }
    }

Borrowed from Dan’s example, when you wrap this component with the Buggy component, componentDidCatch will handle errors thrown. In the example above, we are setting the value of the error and errorInfo states then rendering the content to the browser.

In the App component, update render() to wrap Buggy:

    const App = () => (
      <div style={styles}>

        <h2>Error Boundaries Example</h2>
        <ErrorBoundary>
          <Buggy />
        </ErrorBoundary>
      </div>
    );

Single vs multiple Boundaries

When you wrap a component tree with a single Error Boundary, the entire tree gets affected by errors caught in just one of the components. Take an example:

    class NotBuggy extends React.Component { 
      state = { greeting: "Welcome"};
      render() {
        return <h2>{this.state.greeting}</h2>;
      }
    }

    const App = () => (
      <div style={styles}>
        <h2>Error Boundaries Example</h2>
        <ErrorBoundary>
          <Buggy />
          <NotBuggy />
        </ErrorBoundary>    
      </div>
    );

We’re rendering <Buggy /> and <NotBuggy /> within the same boundary, even though <NotBuggy /> has no error, the Error Boundary doesn’t render it because one of its descendants is buggy.

Here is a demo:

Notice that we still get the same error as before. You can have different Error Boundary trees for a component or a set of components as shown in the image below:

React Error Boundary component tree diagram

Now try separating the two components to have their own respective ErrorBoundary component:

    const App = () => (
      <div style={styles}>

        <h2>Error Boundaries Example</h2>
        <ErrorBoundary>
          <Buggy />
        </ErrorBoundary>

        <ErrorBoundary>
          <NotBuggy />
        </ErrorBoundary>

      </div>
    );

The reason for this behaviour is, according to the React team, it’s safer to tear down the entire component tree and tell the user what went wrong rather than having a corrupt UI which could even lead to a security issue.

Not for all errors

Error Boundaries were introduced to solve a particular problem which we described in the beginning of the post. It was introduced to solve the problem of being unable to handle render errors due to the declarative nature of React components.

That said, do not use Boundaries to handle errors in things like event handlers or other stand-alone logic. Stick to try…catch for such cases as shown in the example below:

    handleClick(e) {
      try {
        JSON.parse(this.state.payload)
      } catch(err) {
        this.setState(...)
      }
    }

Conclusion

It’s easy to migrate to using the new Error Boundaries component. Upgrade React, wrap your component tree with the boundary and start drilling down to find where errors are happening in your existing code base. One confusion you might run into is expecting a Boundary to handle non-component errors which will disappoint you. Know when to use Error Boundaries vs try…catch.

About Chris Nwamba

Chris is a JavaScript preacher. He also strives to make something out of other languages. Tech Writer. Dev Evangelist. Speaker.