Tuesday, August 14, 2018

React Component Lifecycle - getDerivedStateFromProps

The life-cycle method is invoked before calling the render method, both during the initial mounting phase and the update phase. This method returns an object which will be updated in the comgetDerivedStateFromProps ponents state, if no state change is required this method returns null. The main purpose of this method is to update the state based on changes to props.

This is a new life-cycle method introduced in React 16.3, intended to replace the legacy life-cycle method componentWillReceiveProps. This life-cycle method can be used for purposes like displaying Transition animation by comparing previous and next props, handle dynamic scrolling by using previous and next props to decide whether to scroll up or down. This method get called for every render, hence if possible we should avoid using this method with other alternatives.

This life-cycle method is static, hence it does not have access to "this" and we cannot access this.state inside this method, hence it provides the previous state in its 2nd parameter.

Below is the syntax for getDerivedStateFromProps

static getDerivedStateFromProps(props, state) {
    if (props.valueToCheck !== state.valueToCheck) {
      return {
        // state changes to be updated
      };
    } else {
return null; //No state change
}
}

We saw that the new life-cycle method getDerivedStateFromProps replaces the old method componentWillReceiveProps, one notable difference between these two methods is that the old method had reference to both the old props and the new props so that we can compare the prop values directly like
if (this.props.valueToCheck !== nextProps.valueToCheck)

However the new life-cycle method getDerivedStateFromProps does not have a reference to the old props, hence we need to store a copy of the required old props in the state and compare the new prop value with the saved values in the state like
if (props.valueToCheck !== state.valueToCheck)

There are 2 reasons why the old prop values are not retained in the new life-cycle method.

1. A prevProps parameter would be null the first time the mehod is called, this ends us making a Null check.
2. The other reason is related to performance, by not storing the copy of old props we save some memory, thereby improving performance.

Search Flipkart Products:
Flipkart.com

No comments: