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.


componentDidCatch(err, data)


  • err - Error thrown by the component.

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


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.


import React from 'react';

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


This will produce the following result −