Replace componentWillReceiveProps with getDerivedStateFromProps in React

Tram Ho

As in a React blog post, some lifecycle methods will be deprecation . Among them are the methods as shown below:

If you’ve used React since version 16.3 or below, we use a lot of componentWillReceiveProps methods.

Briefly talking about the componentWillReceiveProps method, the main purpose is to Updating state based on props with the passing nextProps of the method to nextProps

For example:

The logic of the code above we will compare nextProps.someValue with this.props.someValue if both are different, we will get the data of nextProps set back to the state , then will handle the logic below.

In essence, the function and function of componentWillReceiveProps is nothing wrong, but it is wrong that we use the function’s param for the wrong purpose.

Some causes below:

  • componentWillReceiveProps will not be called when initial render. The setState needs to be set in the contructor when the component is setState .
  • componentWillReceiveProps will call every time you receive a new Props . So it will setState again whenever the props change even though the props’ data may have to be setState unchanged.
  • componentWillReceiveProps is synchronous but setState() asynchronous . What happens when a function synchronous calls multiple times to process the function asynchronous

So getDerivedStateFromProps was born to handle these problems

getDerivedStateFromProps is a static method asynchronous , it will not need any rendering conditions. It will call every time the component created or every time when the props or state changed.

getDerivedStateFromProps will return new state otherwise if the state doesn’t change it will return null

In addition, because getDerivedStateFromProps is a static method, you cannot call this inside this method or you simply cannot call the setState() function here without this . So you need to combine with componentDidUpdate to setState

For example:

A question arises why in getDerivedStateFromProps does not pass the previous props getDerivedStateFromProps param?

Because of the following 2 reasons:

  • When the first getDerivedStateFromProps invoke the previous props will then be null, but getDerivedStateFromProps requiring check if-not-null
  • A step to freeing up memory in React. If we didn’t pass the previous props into the param then React wouldn’t need to keep the props in memory.

Above I have introduced about getDerivedStateFromProps

Thank you for watching !

Ref: -getderivedstatefromprops-c3956f7ce607

Share the news now

Source : Viblo