React documentation says:
componentDidUpdate() is invoked immediately after updating occurs.This method is not called for the initial render.
Use this as an opportunity to operate on the DOM when the componenthas been updated. This is also a good place to do network requests aslong as you compare the current props to previous props (e.g. anetwork request may not be necessary if the props have not changed).
This is important for you:
You may call setState() immediately in componentDidUpdate() but notethat it must be wrapped in a condition like in the example above, oryou’ll cause an infinite loop.
You must not use the setstate without condition, setting state in componentDidUpdate will cause the infinite loop.
I would say completely avoid them.
Which method to use?
If you are using previous version then 16.3 use componentWillReceiveProps
If you are using 16.3 or above then use getDerivedStateFromProps
Here is an interesting conversation to read
Update as per comment:
You need to be specific when applying the condition, this.state !== prevState` is not enough.
Let say you have this.state.counter = 1 and you are updating the into componentDidUpdate
and incrementing this.state.counter as 2.
This will always results into infinite loop.