ReactJS componentDidCatch method


In this article, we are going to see how to execute a function in the commit phase if some error occurs in the Component.

This method is called when a component or any children component encounters some error during the React Component Lifecycle. This method allows us to handle the error boundaries of the application.

Unlike the getDerivedStateFromError method, this method is called during the commit phase, so side-effects are also allowed in this method.

Syntax

componentDidCatch(err, data)

Parameters

  • err - Error thrown by the component.

  • data - Stores information about the component which has thrown the error.

Example

In this example, we will build a React application that displays the contained Comp component if no error occurs; otherwise it displays some text.

But here, in Comp component, error is defined to occur as the state is not defined which fires the componentDidCatch method in the parent component.

App.jsx

import React from 'react';

class App extends React.Component {
   constructor() {
      super();
      this.state = {
         err: false,
      };
   }
   componentDidCatch(error) {
      this.setState({
         err: true,
      });
   }
   render() {
      return (
         <div>
            {this.state.err ? (
               <div style={{border: '2px solid red',}}>
                  Error
               </div>
               ) : (
               <Comp/>
            )}
         </div>
      );
   }
}
class Comp extends React.Component {
   render() {
      return <h1>{this.state.name}</h1>;
   }
}
export default App;

Output

This will produce the following result −

Updated on: 18-Mar-2021

979 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements