4

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

Nguyen DN
  • 140
  • 1
  • 2
  • 11
  • 1
    Please include a [Minimal, Complete, and Verifiable example](https://stackoverflow.com/help/mcve), or it will be very difficult to help you. – Tholle Nov 15 '18 at 18:09
  • 1
    The reason for a component to call componentDidUpdate() is this its state or props has been updated. This is caused by calling setState() in your component or the parent's component changing its props to your component. – Shawn Andrews Nov 15 '18 at 18:17
  • ...or parent is re-rendered and this concrete child is not `PureComponent` so it's re-rendered too – skyboyer Nov 15 '18 at 18:37

2 Answers2

8

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.

koo
  • 4,013
  • 6
  • 15
  • 31
  • I don't understand why `if (prevProps.something !== something) this.apiCall();` may not be satisfied anymore and console logging would trigger infinite loop. – SoftTimur Jan 13 '23 at 04:34
5

componentDidUpdate() is invoked immediately after updating occurs.

your problem may be accorded because the state has been changed, props received or parent re-rendred.

if you are new with React, I recommend you to read the following article: Post-Render with componentDidUpdate()

Nir Berko
  • 1,368
  • 1
  • 13
  • 33