1
votes
constructor(props) {
    super(props);
    this.state = {
        myStateVar: []
    }
}

static getDerivedStateFromProps(props, state) {
    if (props.myStateVar !== state.myStateVar) {
        return {
           myStateVar: props.myStateVar
        }
    }

    toggle() //Need to call the function each time when we get the props update
    return null;
}

toggle() {
    this.setState({
        otherStateVar: []
    })
}

I am migrating my react app from 16.3 to latest. I have a problem where getDerivedStateFromProps() is calling continuously because state is updating in toggle(). I need to call the toggle() when the props got updated

Help me out to resolve the problem.

2
You can use componentDidUpdate for this.Vishnu
componentDidUpdate won't get the prop changes/updates right ?Mallikarjuna
componentDidUpdate will be called with prevProps as argument. You can check the condition there. I've added an answer which reflects itVishnu

2 Answers

1
votes

getDerivedStateFromProps is run on every render. It is also a static method, so it shouldn't be called setState (or other non-static functions). In the documentation, React points out that most of the time you don't need this method to achieve state change based on prop changes here.

So first option, don't call setState, it triggers a re-render and a re-render will run getDerivedStateFromProps. Essentially an infinite re-render loop.

static getDerivedStateFromProps(props, state) {
    if (props.myStateVar !== state.myStateVar) {
        return {
           myStateVar: props.myStateVar,
           otherStateVar: [] // from toggle
        }
    }

    // Should not be called everytime this method runs. Only when props change
    // toggle() //Need to call the function each time when we get the props update
    return null;
}

Your other option is memoization which is covered pretty thoroughly in that link I provided.

1
votes

Why don't you use componentDidUpdate for this? It seems to me you can achieve the result by:

/**
 * @param {Props} prevProps props of the component
 **/
componentDidUpdate(prevProps) {
  if (prevProps.myStateVar !== this.props.myStateVar) {
    this.setState({ myStateVar: this.props.myStateVar });
    toggle();
  }
}