How to use error boundary in react?

Error boundary catch errors in components below their component tree in declarative fashion. You can also use try/catch to catch and handle the errors in React, but that is applicable only for imperative code.

try{
...
...
}catch(e){
// handle error here
}

But error boundary allow you to wrap the components so that error is contained inside them, and do not break the whole application.

A class component becomes an error boundary if it defines either (or both) of the lifecycle methods static getDerivedStateFromError() or componentDidCatch(). Use static getDerivedStateFromError() to render a fallback UI after an error has been thrown. Use componentDidCatch() to log error information.

Using componentDidCatch

We are going to create a class with ComponentDidCatch method, and insert a child component inside it. This child component will have a error, but the main application is not broken because of it.

In the above example, we created two child components called ChildComponent1 and ChildComponent2. The ChildComponent1 has componentDidCatch method implemented. Because of this, even though there is error in ChildComponent1, it does not break the entire application, and you can see the output of ChildComponent2.

Components 1 and 2 inside main application.
Components 1 and 2 inside main application.

Here is the code of ChildComponent1

import React, { Component } from "react";

export default class ChildComponent1 extends Component {
  // error is contained inside ChildComponent because of componentDidCatch
  componentDidCatch(error) {
    console.log(error);
  }

  render() {
    return <ChildComponent />;
  }
}

class ChildComponent extends Component {
  render() {
    return <h1>{this.state.title}</h1>;
  }
}


Using getDerivedStateFromError

getDerivedStateFromError , just like getDerivedStateFromProps, allow you to get new state based upon error (or props). You can use this state to render some fallback UI. Like in the above example, we used componentDidCatch method in ChildComponent1 to catch the error, but we can also use getDerivedStateFromError to know when the error occurred, and show some error message to the user.

When to use getDerivedStateFromError and componentDidCatch?

componentDidCatch is a lifecycle method called when error occurs. You can use this method to write some side-effect code like logging the error to some API service.

In getDerivedStateFromError, you get the state when error occurs. This state can be used to render some fallback UI for error.

But you can also set the state in componentDidCatch, and have the same functionality of showing fallback UI for error. Setting state in componentDidCatch is not encouraged, and it is going to be depreciated from newer versions of React.

To understand more about why you should not set state in componentDidCatch, read this blog.