Showing posts with label componentWillReceiveProps. Show all posts
Showing posts with label componentWillReceiveProps. Show all posts

Tuesday, August 14, 2018

componentWillReceiveProps example

The componentWillReceiveProps life-cycle method is used to check any change in prop values and update the state of the component if required. This life-cycle method has access to both the previous set of props and new set of props hence we can compare them and update the state if required.

The componentWillReceiveProps life-cycle method will get deprecated, React 16.3 introduced a new life-cycle method getDerivedStateFromProps, which should be used to check prop value changes going forward.

The following example uses componentWillReceiveProps() to check the value of the prop "parentColor", compare the previous value of the prop and the current value of the prop and updates the state if the prop was changed. Any change in state value updates the color of the box displayed in the UI.

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