How to Use the React componentDidCatch() Method

09/28/2021

Contents

In this article, you will learn how to use the React componentDidCatch() method.

Using the componentDidCatch() method

The componentDidCatch() method is a lifecycle method in React that allows you to handle errors that occur during rendering. It is called when there is an error in any of the child components of the current component. You can use componentDidCatch() to catch errors and handle them in a graceful manner. Here is a step-by-step guide on how to use the componentDidCatch() method in your React application.

Create an error boundary component

To use componentDidCatch(), you need to create an error boundary component. An error boundary component is a component that wraps around other components and catches errors that occur within those components. You can create an error boundary component by creating a new class that extends React.Component.

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

  componentDidCatch(error, info) {
    this.setState({ hasError: true });
    console.error(error, info);
  }

  render() {
    if (this.state.hasError) {
      return 

Something went wrong.

; } return this.props.children; } }

Wrap your components in the error boundary component

Once you have created the error boundary component, you need to wrap your components that you want to catch errors in with the ErrorBoundary component. This can be done by simply wrapping your components in the ErrorBoundary component as shown below:

<ErrorBoundary>
  <MyComponent />
</ErrorBoundary>

Test your error handling

Now that you have wrapped your component in the ErrorBoundary component, you can test your error handling by intentionally causing an error in the component. You can do this by adding a method to the component that throws an error.

class MyComponent extends React.Component {
  handleClick() {
    throw new Error('Something went wrong');
  }

  render() {
    return ;
  }
}

When you click on the button in the component, it will throw an error, and the componentDidCatch() method in the ErrorBoundary component will be called. This will set the state of the ErrorBoundary component to hasError: true, and the message “Something went wrong” will be displayed.