CodeZombie
CodeZombie

Reputation: 2087

What is the best way to compare between the many prevProps and nextProps in Reactjs?

The child component is receiving many updated props from its parent component.I want to update the child component if there is any update in the props.Currently,i'm doing it using the life cycle method componentWillReceiveProps which is working as expected.

componentWillReceiveProps(nextProps){
    if(this.props.scale_length !== nextProps.scale_length){
      const {scale_height,scale_breadth} = this.props
      this.setState({
        torsoScale: new 
            THREE.Vector3(nextProps.scale_length,scale_height,scale_breadth)
      });
    }
if(this.props.scale_breadth !== nextProps.scale_breadth){
      const {scale_height,scale_length} = this.props
      this.setState({
        torsoScale: new 
            THREE.Vector3(scale_length,scale_height,nextProps.scale_breadth)
      });
    }

...
}

But,i would be getting 8+ props in the future.How would i proceed with that.Thanks.

Upvotes: 0

Views: 1812

Answers (1)

We Are All Monica
We Are All Monica

Reputation: 13334

I want to update the child component if there is any update in the props.

This is what React does by default! You should work with its normal component updates rather than trying to fight against it and decide whether to update things yourself.

You can use getDerivedStateFromProps for this, but there are probably better ways still, like just computing the vector directly in the render method.

Here is an article with lots more detail: https://reactjs.org/blog/2018/06/07/you-probably-dont-need-derived-state.html

Upvotes: 1

Related Questions