ReactJS componentDidCatch() Method (original) (raw)

Last Updated : 10 Aug, 2021

The componentDidCatch() method is invoked if some error occurs during the rendering phase of any lifecycle methods or any children components. This method is used to implement the Error Boundaries for the React application. It is called during the commit phase, so unlike getDerivedStateFromError() which was called during the render phase, side-effects are allowed in this method. This method is also used to log errors.

Syntax:

componentDidCatch(error, info)

Parameters: It accepts two parameters i.e, error, and info as described below:

Creating React Application:

Step 1: Create a React application using the following command:

npx create-react-app foldername

Step 2: After creating your project folder i.e. folder name, move to it using the following command:

cd foldername

Project Structure: It will look like the following.

Project Structure

Example: Program to demonstrate the use of componentDidCatch() method.

Filename: App.js:

JavaScript `

import React, { Component } from 'react';

export default class App extends Component { // Initializing the state state = { error: false, };

componentDidCatch(error) { // Changing the state to true // if some error occurs this.setState({ error: true }); }

render() { return ( <React.StrictMode>

{this.state.error ?
Some error
: }
</React.StrictMode> ); } }

class GFGComponent extends Component {

// GFGComponent throws error as state of // GFGCompnonent is not defined

render() { return

{this.state.heading}

; } }

`

Step to Run Application: Run the application using the following command from the root directory of the project:

npm start

Output:

output

Reference: https://reactjs.org/docs/react-component.html#componentdidcatch