why componentDidUpdate run multiple times

Nguyen DN picture Nguyen DN · Nov 15, 2018 · Viewed 9.1k times · Source

I really don't understand the react life cycle. I run console.log in componentDidUpdate() and saw that it ran multiple times Console showed that componentDidUpdate ran 3 times

Answer

koo picture koo · Mar 1, 2019

Maybe I can give you an extra example when your issue happens since I cannot see your code.

componentDidUpdate(prevProps, prevState) {
        const { something } = this.props;
        if (prevProps.something !== something) this.apiCall();
        console.log('something')
}

when you change your state or props, componentDidUpdate is being invoked, and apiCall function makes http request via fetch or axios, and change the state twice using setState function.

whenever state gets changed, new render() is being invoked and componentDidUpdate follows.

but the condition

if (prevProps.something !== something) this.apiCall();

may not be satisfied anymore, just console logging at this time instead of calling apiCall function which would trigger inifinite loop.

hope it helps.