Search code examples
reactjsgetderivedstatefromprops

How to skip the update of state inside getDerivedStatefromProps() in childComponent only for the first time of rendering the childComponent


Hi I'm new to Reactjs. I want {this.state.data} of the below childComponent to be incremented 5 on each time this component is getting loaded. So i'm doing that under the static method getDerivedStateFromProps(props,state) But for the first time when it is loading {this.state.data} should be the initial value i have defined (Here it is 0). So i'm expecting the below line output to be incremented 5 starting from 0(initial value i defined)

Data from ClassChild : {data}

Expected Output: Data from ClassChild : 0 Data from ClassChild : 5 Data from ClassChild : 10 Data from ClassChild : 15

Actual Output: Data from ClassChild : 5 Data from ClassChild : 10 Data from ClassChild : 15 Data from ClassChild : 20

Is there anyway to skip the first time execution of getDerivedStateFromProps(props,state), instead of defining the -5 value in constructor to get the expected output?

class ClassChild extends Component{
    constructor(props){
        super(props)
        console.log("ClassChild constructor()")
        this.state = {
            data : 0
        }
    }
    static getDerivedStateFromProps(props,state){
        console.log("ClassChild getDerivedStateFromProps()")
        return {
            data : state.data + props.childIncState
        }
    }
    render(){
        const {count, childIncState} = this.props
        const {data} = this.state
        return(
            <div>
                <div>Count from ClassParent : {count}</div>
                <div>Value to be incremented in ClassChild : {childIncState}</div>
                <div>Data from ClassChild : {data}</div>
                {console.log("ClassChild render()")}
            </div>
        )
    }
}
export default ClassChild;```


Solution

  • You should use componentDidUpdate(). It is not called for the initial render.

    Here is an example:

    componentDidUpdate(prevProps) {
       if(prevProps.childIncState !== this.props.childIncState) {
          setState({data: this.state.data + props.childIncState});
       }
    }