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.


static getDerivedStateFromError(error)

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


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.


import React, { Component } from 'react';

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


This will produce the following result.

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