J Seabolt
J Seabolt

Reputation: 2988

Props updated, componentDidUpdate did not fire

Is there ever a situation where componentDidUpdate would NOT fire, even if the props updated in React?

Upvotes: 8

Views: 10918

Answers (5)

Sankozi
Sankozi

Reputation: 568

Nathan response is correct but it did not solve my problem when I searched for the same answers.

Sometimes it looks like props are updated but it is whole new component rendered with different props. Check componentDidMount (add console.log in it for example) to see what exactly happens.

Upvotes: 2

Nathan_
Nathan_

Reputation: 41

A common situation where this occurs is when multiple prop changes occur which don't effect anything in the virtual DOM.

For example you may wish to display a success message if an API returns 200 status code, with props that change like this:

API not called:

this.props.apiState == false

API called:

this.props.apiState == 'loading'

API successful:

this.props.apiState == 'success'

In this situation componentDidUpdate will only fire once, and if you console log this.props.apiState at the time it is fired you will see that it is loading. So any trigger in componentDidUpdate that is waiting on success will not occur.

ComponentWillReceiveProps deals with this issue in older versions of React, and in newer versions of React you can use shouldComponentUpdate to force an update when your desired prop change occurs.

Upvotes: 4

Antonios
Antonios

Reputation: 129

this can also happen, if your component is in a list and the key of your component changes (ie. on every render) or the key is missing, or the key is duplicate, etc.

refer to docs for details: https://reactjs.org/docs/lists-and-keys.html

Upvotes: 4

ugrpla
ugrpla

Reputation: 403

You can suppress a render with returning false in shouldComponentUpdate(). So yes, in that case componentDidUpdate() won't fire.

Upvotes: 3

Nathan Christian
Nathan Christian

Reputation: 396

There are 3 conditions that can cause componentDidUpdate to not fire:

1) You wrote a custom shouldComponentUpdate that returned false.

2) The internal react methods determined that there was no change in the virtual DOM, so it chose not to re-render.

3) You extended something other than React.Component (such as PureComponent) which has a default shouldComponentUpdate method that returned false.

Upvotes: 7

Related Questions