Mallikarjuna
Mallikarjuna

Reputation: 401

react js getDerivedStateFromProps is calling continuously

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.

Upvotes: 2

Views: 864

Answers (2)

Vishnu
Vishnu

Reputation: 1701

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();
  }
}

Upvotes: 2

Spidy
Spidy

Reputation: 40002

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.

Upvotes: 1

Related Questions