Skip to content
Related Articles

Related Articles

Save Article
Improve Article
Save Article
Like Article

ReactJS getDerivedStateFromError() Method

  • Last Updated : 16 Oct, 2021

The getDerivedStateFromError() 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 render phase, so side-effects are not permitted in this method. For side-effects, use componentDidCatch() instead. 


static getDerivedStateFromError(error)

Parameters: It accepts the error that was thrown as a parameter.

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

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

Project Structure: It will look like the following. 


Filename: App.js


import React, { Component } from 'react';
export default class App extends Component {
  // Initializing the state
  state = {
    error: false
  static getDerivedStateFromError(error) {
    // Changing the state to true if some error occurs
    return {
      error: true,
  render() {
    return (
          {this.state.error ? <div>Some error</div> : <GFGComponent />}
class GFGComponent extends Component {
  // GFGComponent throws error as state of GFGCompnonent is not defined
  render() {
    return <h1>{this.state.heading}</h1>;


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

npm start




My Personal Notes arrow_drop_up
Recommended Articles
Page :