Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
...instead of
componentWillReceiveProps
.Originally
componentWillReceiveProps
was used to allowsetState
calls to resolve before the next render, in order to avoid double-rendering. This is a bit of an edge case and updates which cause double-rendering aren't considered "best practice" with React in anyway (I'll explain below).Changing to
componentDidUpdate
makes the update behavior consistent with first mount (in both cases a render has already happened whenreceiveProps
is called and the DOM update is complete), allowing functions likefindDOMNode
to reliably select the rendered element which represents the current state of the component's props. Without this change you either have to avoid ever altering the root node or run the logic in asetTimeout
(not reliable).On the note about "best practice" --
Props shoudn't determine state without a good reason, i.e. some info that isn't available directly in the props themselves and is expensive to compute. When a prop is copied directly into state every time it changes (or even just sometimes), it produces two sources for that value. Which one "owns" it? If the component state is the source of truth, changes to props will get ignored. If the parent owns it, copying it into the component state is pointless. If the parent owns it but the child needs to be able to change it, the parent should also be passing down a callback for updating the value it owns, rather than having a child clone it.
If the value is expensive to compute but otherwise available in the props, prefer a memoizing helper (a Memoize component that takes a render prop is a good idea). If the value is not readily available from the props alone (maybe an API call or user input is needed), the update is already going to be asynchronous and double-rendering is unavoidable (even desirable, indicate that loading state).
More info: You probably don't need derived state