Home > Back-end >  Why and how is state being set this way inside `getDerivedStateFromError`?
Why and how is state being set this way inside `getDerivedStateFromError`?

Time:10-06

I'm learning about ErrorBoundaries in React and was wondering why and how in the getDerivedStateFromError method, is state being set this way?

// REACT
import React from 'react';

export class ErrorBoundary extends React.Component {

  state = {
    isThereError: false
  }

  static getDerivedStateFromError(error) {
    return {
      isThereError: true 
    };
  }

  // ...

};

Shouldn't it be:

// REACT
import React from 'react';

export class ErrorBoundary extends React.Component {

  state = {
    isThereError: false
  }

  static getDerivedStateFromError(error) {
    
    this.setState({ isThereError: true })

  }

  // ...

};

CodePudding user response:

State isn't being set in the method itself. But by convention the framework expects that method to return an updated state object. The framework then internally uses that result to update state:

This lifecycle is invoked after an error has been thrown by a descendant component. It receives the error that was thrown as a parameter and should return a value to update state.

So when implementing getDerivedStateFromError in your component you don't need to worry about updating state within that method. Just return the new state.

  • Related