ReNinja
ReNinja

Reputation: 573

Call a method after the state changes by getDerivedStateFromProps in react js

I have a react component in which I need to call a method after the state changes in the getDerivedStateFromProps. Let's say I have a method foo to be called after the state changes in the getDerivedStateFromProps.

//state
state: {
    "a": "",
    "b": ""
}

static getDerivedStateFromProps(nextProps, currentState){
    if(nextProps.show){
        // nextProps.foo() function to be called after the state changes to "a": "Apple","b": "Ball"
        return {
            "a": "Apple",
            "b": "Ball"
        }
    }
}
//The function in parent component
foo = () => {
    console.log("Function called")
}

Upvotes: 2

Views: 335

Answers (2)

Ashish Singh
Ashish Singh

Reputation: 754

I am not sure why exactly are you using a getDerivedStateFromProps life cycle hook.
I am sure you realize that Deriving state leads to verbose code and makes your components difficult to think about.

On a side note, if the only requirement you have is to run a parent function while certain props update or local state updates, you might want to try life cycle hook, componentDidUpdate

Have a look at the code snippet,

componentDidUpdate(prevProps, prevState) {
    //check for update in props
    if(prevProps.show !== this.props.show){
        //call the parent function
        this.props. foo()
    }
}

In case you have to use getDerivedStateFromProps, think of it like this, since the life cycle method essentially returns an object which would update the state object. You could have a componentDidUpdate to listen for state changes and call the parent prop function.

componentDidUpdate(prevProps, prevState){
    //check for update in state after derived state
    if( (prevState.a !== this.state.a) || (prevState.b !== this.state.b) ){
        //call the parent function
        this.props.foo()
    }
}

In any case, you should read more about getDerivedStateFromProps life cycle hook from the official documentation by clicking HERE

Upvotes: 1

artfulbeest
artfulbeest

Reputation: 1483

Invocation of props.foo() depends on props.show, so you can use componentDidUpdate lifecycle method.

componentDidUpdate(prevProps) {
    if (this.props.show !== prevProps.show && this.props.show) {
      this.props.foo();
    }
  }

which means props.foo will be called when props.show changes and props.show is true

Upvotes: 1

Related Questions