ReactJS – getDerivedStateFromError() Method

ReactJSWeb DevelopmentFront End Technology

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

This method is called when a component encounters some error during the React Component Lifecycle. This method allows us to handle the error boundaries of the application. To avoid performance issues, don’t set up any side-effects in this method.

Syntax

static getDerivedStateFromError(error)

It accepts the error as a parameter that was thrown as a component.

Example

In this example, we will build a React application that displays the contained Comp1 component if no error occurs; otherwise it displays some text. But here, in Comp1 component, error is defined to occur, as the state is not defined which fires the getDerivedStateFromError in the parent component.

App.jsx

import React, { Component } from 'react';

class App extends Component {
   constructor(){
      super();
      this.state = {
         err: false
      };
   }
   static getDerivedStateFromError(error) {
      // Changing the state if some error occurs
      return {
         err: true,
      };
   }
   render() {
      return (
         <div>
            {this.state.err ? <div>Some Error Occurred</div> : <Comp1 />}
         </div>
      );
   }
}
class Comp1 extends Component {
   render() {
      return <h1>{this.state.data}</h1>;
   }
}
export default App;

Output

This will produce the following result.

raja
Published on 18-Mar-2021 11:54:07

Advertisements