The main difference between the two is:
- When they are called in a component’s lifecycle
- How it updates component
When are they called?
As the names suggest – and as you probably know since you mentioned “if I do setState in componentDidUpdate, render will trigger twice” –
componentDidUpdate is called after the component updates (received new props or state). This is why the parameters to this function is
So if you wanted to do something before the component received new props, you’d use
componentWillReceiveProps, and if you wanted to do something after it received new props or state, you’d use
How do they update
The main difference here is:
componentWillReceivePropswill update state synchronously
componentDidUpdatewill update state asynchronously.
This can be important as there are some gotchya’s that can come up when trying to sync state with other parts of your component’s props.