getDerivedStateFromProps() in ReactJS

static getDerivedStateFromProps(props, state) is a static method which is called just before render() method in both mounting and updating phase.

getDerivedStateFromProps(props, state) takes updated props and current state as arguments.

You need to return an object to update state or null to indicate that nothing has changed.

Why getDerivedStateFromProps() should be used?

When state of component depends on changes of props, then this method is used.

Let us have a look at an example.


import React from 'react';
import ReactDOM from 'react-dom';

class Counter extends React.Component{
    constructor(props){
        super(props);
        this.state = {
        };
    }
    static getDerivedStateFromProps(nextProps, state) {
        if(nextProps.someValue !== state.mirroredValue){
            //Change in props
            return{
                mirroredValue: nextProps.someValue
            };
        }
        return null; // No change to state
    }
    /* if props changes then after getDerivedStateFromProps method, state will look something like 

    {
        mirroredValue: someValue
    }
    */
    render(){
        ...
    }
}
                    

In above code, if props changes, then state will also change accordingly else, getDerivedStateFromProps will return null that indicates no change in state.

Points to remember while using getDerivedStateFromProps

getDerivedStateFromProps is used in some rare cases where state depends on the change of props. There are some points to remember while using getDerivedStateFromProps.

  • getDerivedStateFromProps is a static method. So it does not have access to component instance this. It has only updated props and current state object.
  • If you need to do anything after state update like fetching data, then you should use componentDidUpdate lifecycle method.
  • getDerivedStateFromProps method is available in ReactJS Version 16.3 or greater.

Conclusion

In this section, we learned about getDerivedStateFromProps and for what it can be used.
In the next section, you will learn about render() method of ReactJS component.