Easy Tutorial
❮ React Ref Shouldcomponentupdate React Props ❯

React getDerivedStateFromProps() Method

React Component Lifecycle

The getDerivedStateFromProps() method has the following format:

static getDerivedStateFromProps(props, state)

getDerivedStateFromProps is invoked right before calling the render method, both on the initial mount and on subsequent updates. It should return an object to update the state, or null to update nothing.

The value of state depends on props at any time.

The sole purpose of getDerivedStateFromProps is to allow a component to update its internal state in response to changes in props.

This method returns an object to update the state, or null if no updates are needed.

In the following example, the initial value of favoritesite is tutorialpro, but the getDerivedStateFromProps() method updates the value of favoritesite via the favsite property:

Example

class Header extends React.Component {
  constructor(props) {
    super(props);
    this.state = {favoritesite: "tutorialpro"};
  }
  static getDerivedStateFromProps(props, state) {
    return {favoritesite: props.favsite };
  }
  render() {
    return (
      <h1>My favorite website is {this.state.favoritesite}</h1>
    );
  }
}

ReactDOM.render(<Header favsite="Google"/>, document.getElementById('root'));

Example

class Header extends React.Component {
  constructor(props) {
    super(props);
    this.state = {favoritesite: "tutorialpro"};
  }
  static getDerivedStateFromProps(props, state) {
    return {favoritesite: props.favsite };
  }
  changeSite = () => {
    this.setState({favoritesite: "google"});
  }
  render() {
    return (
      <div>
      <h1>My favorite website is {this.state.favoritesite}</h1>
      &lt;button type="button" onClick={this.changeSite}>Change Site Name</button>
      </div>
    );
  }
}

ReactDOM.render(<Header favcol="taobao"/>, document.getElementById('root'));

React Component Lifecycle

❮ React Ref Shouldcomponentupdate React Props ❯