I am looking for an explanation of parameters for each component method such as componentDidUpdate(). I see the link https://reactjs.org/docs/react-component.html#componentdidupdate but it does not provide any explanation of the parameters such as prevProps, prevState, and snapshot. Where can I find documentation that describes them?
Is my current understanding of the parameters correct?
prevProps: The props object before render() was called by a change in either state or props.
prevState: The state object before render() was called by a change in either state or props.
snapshot: ???
prevState and prevProps are the state and props from the previous render cycle, as opposed to this.state and this.props from the current render cycle.
The snapshot comes from getSnapshotBeforeUpdate
Any value returned by this lifecycle will be passed as a parameter to
componentDidUpdate().
You can find the react component documentation here.
Aside from the documentation there are a few good blog posts on the web explaining the various lifecycle methods, when to use them and how they work:
https://blog.logrocket.com/the-new-react-lifecycle-methods-in-plain-approachable-language-61a2105859f3/
https://engineering.musefind.com/react-lifecycle-methods-how-and-when-to-use-them-2111a1b692b1?gi=3ac3c7c8ff34
A far as I know there is no other, more specific documentation about lifeCycleMethods.
Parameters such as prevProps and prevState are pretty much self-explanatory. Even if someone isn't sure what they are, console.log(prevProps, prevState) could help. My assumption is that self-explanatory nature of these parameters is what makes them ommited from detailed explanation in docs.
On the other hand, snapshop which is not that much self-explanatory is explained:
If your component implements the getSnapshotBeforeUpdate() lifecycle (which is rare), the value it returns will be passed as a third “snapshot” parameter to componentDidUpdate(). Otherwise this parameter will be undefined.
Related
Recently I took an online test where the following question was asked:
Which of the following methods is not executed while mounting a React Component?
constructor()
render()
componentWillReceiveProps()
componentDidMount()
I believe all of these methods will get executed while mounting a React Component. But I did select option 4. componentDidMount() even though it is wrong as I had to select an option and yes the online test said it is wrong. According to an article on Pluralsight all of the above methods will execute on mounting (componentWillReceiveProps() is deprecated and static getDerivedStateFromProps() should be used).
What I do not understand is
Is the question wrong?
Are the options wrong?
My understanding of the question is wrong?
I am confused. Please help me get the right perspective.
Thanks in Advance.
The documentation for componentWillReceiveProps says
is invoked before a mounted component receives new props.
It operates on a already mounted component receiving new props. A component being mounted cannot receive new props until it has initial props.
Also note that getDerivedStateFromProps is not a 1 for 1 replacement method. It is suggested as an alternative for operations that were typically done in componentWillReceiveProps, but they do not do the same thing.
Phases of React Life Cycle methods
Mounting
constructor
static getDerivedStateFromProps()
render()
componentDidMount()
Updating
static getDerivedStateFromProps()
shouldComponentUpdate()
render()
getSnapshotBeforeUpdate()
componentDidUpdate()
unmounting
componentWillUnmount()
You can check the official documentation for a better understanding - the-component-lifecycle
I am learning to react lifecycle methods but stuck at a query and not able to find the answer even after lots of research over the web.
As per the react official documentation here, it is said that the method getSnapshotBeforeUpdate is used to perform something just before the DOM commit. The snapshot returned by this function will be later used by componentDidUpdate.
The query:
The parameters 'prevProps' and 'prevState' are already present in method componentDidUpdate, then why does it need the help of function getSnapshotBeforeUpdate? I mean the function componentDidUpdate has necessary inputs to perform what getSnapshotBeforeUpdate is doing.
Any help would be appreciated.
Best,
Rahul
As clearly mentioned in the documentation with an example, the purpose of getSnapshotBeforeUpdate method is not to just get information from prevProps and/or prevState.
But it can be used to extract some information from the previous DOM (such as the current scroll position of a div) before the DOM is updated. Most cases, such DOM related values may not be covered by the prevProps or prevState.
When you consider only the componentDidUpdate method, the DOM has already updated (hence the name DidUpdate) when it's been called. So all the information related to the previous DOM has lost by that time.
Therefore the extracted information on previous DOM from getSnapshotBeforeUpdate can be passed to the componentDidUpdate method to use it there.
componentWillRecieveProps is deprecated and getDerivedStateFromProps is being advocated to use.
But componentWillRecieveProps gets called when the props get changed but getDerivedStateFromProps is getting called on any state change even.
My requirement is to reset state on props change. So how would I get to know if the props really got changed.
I am not in favor of storing the props value in state as it would unnecessarily make the state bulkier and I still not have given state management(Redux or Context API) a thought
Please advise
how would I get to know if the props really got changed.
Compare previous prop with new prop.
For simplest use case, just use componentDidUpdate(), with prop comparing:
componentDidUpdate(prevProps) {
// Typical usage (don't forget to compare props):
if (this.props.userID !== prevProps.userID) {
this.fetchData(this.props.userID);
}
}
According to React Doc, it is OK to perform side effect or setState() inside componentDidUpdate().
And setState() can cause re-rendering, which affects component performance. When performance in this case is actually a thing, read on: https://reactjs.org/blog/2018/06/07/you-probably-dont-need-derived-state.html#when-to-use-derived-state
componentWillReceiveProps(nextProps) {
// Check to see if the requestRefresh prop has changed
if (nextProps.requestRefresh !== this.props.requestRefresh) {
this.setState({loading: true}, this.updateData);
}
}
As far as my understanding goes, this lifecycle hook is called when a Component's properties are updated by the parent.
This piece of code checks if the requestRefresh property is different (one to update and one that it currently has)
Now what i dont understand is this , this.updateData);
why is this with the setState method. Please help me understand
Secondly where does prevState come from and which lifecycle hook can update it
the setState method can be called with a callback as its second parameter, mainly to handle operations which need to be done when the state is fully updated.
In your example this.updateData is the callback.
setState's first argument is also a function, with the signature (prevState, props) => stateChange, this is allowing you to get access to the previous state when performing updates.
You may want to check the official doc for further details :
https://reactjs.org/docs/react-component.html#setstate
The React maintainers discourage the use of componenetWillReceiveProps.
From the React docs:
It is recommended that you use the static getDerivedStateFromProps lifecycle instead of UNSAFE_componentWillReceiveProps. Learn more about this recommendation here.
To answer your question: prevstate is the previous state, so it is the state of your component before new props are received which in turn might chnage the new state. You can also hanlde prevstate in the static getDerivedStateFromProps method:
static getDerivedStateFromProps(nextProps, prevState)
getDerivedStateFromProps is invoked after a component is instantiated as well as when it receives new props. It should return an object to update state, or null to indicate that the new props do not require any state updates.
What are the implications of doing this?
class Foo extends React.Component {
componentWillUpdate(nextProps, nextState) {
nextState.bar = transformSomehow(nextState.foo);
}
}
My gut tells me that this is wrong, but I haven't found any documentation saying that nextProps and nextState should be read-only, nor have I found anything saying that this is ok.
The idea here is that I want some kind of sanitized/transformed/modified version of data from state. There are probably plenty of other (better) ways to do this, but is this also a viable option?
I would say that this is not an ideal approach because you are trying to mutate state. You should not call setState from within componentWillUpdate, nor should you try to update your state object at this point. This stage is used more for animations, DOM manipulations, etc.
If you want to set some other vars based on nextState, go for it. If you want to work ad hoc copies of state to get something done, all good. But I think that attempting to mutate state in this method runs counter to the intended use of this lifecycle method. From the docs on componentWillUpdate:
Note that you cannot call this.setState() here. If you need to update state in response to a prop change, use componentWillReceiveProps() instead.