This is how we use componentWillReceiveProps
componentWillReceiveProps(nextProps) {
if(nextProps.myProp !== this.props.myProps) {
// nextProps.myProp has a different value than our current prop
}
}
It's very similar to componentDidUpdate
componentDidUpdate(prevProps) {
if(prevProps.myProps !== this.props.myProp) {
// this.props.myProp has a different value
// ...
}
}
I can see some differences, like if I do setState in componentDidUpdate, render will trigger twice, and the argument for componentWillReceiveProps is nextProps, while argument for componentDidUpdate
is prevProp, but seriously I don't know when to use them. I often use componentDidUpdate
, but with prevState, like change a dropdown state and call api
eg.
componentDidUpdate(prevProps, prevState) {
if(prevState.seleted !== this.state.seleted) {
this.setState({ selected: something}, ()=> callAPI())
}
}
The componentDidUpdate()is called after componentDidMount() and can be useful to perform some action when the state of the component changes. Parameters: Following are the parameter used in this function: prevProps: Previous props passed to the component. prevState: Previous state of the component.
ReactJS – componentWillReceiveProps() Method This method is used during the updating phase of the React lifecycle. This function is generally called if the props passed to the component change. It is used to update the state in response with the new received props.
The componentWillReceiveProps() method is being deprecated in future version of React (17). Many of us use this method day-to-day to check for incoming prop changes, store state, and to invoke side effects like logging or fetching data from a server.
getDerivedStateFromProps is one of those newly introduced lifecycle method replacing componentWillReceiveProps , which has now become UNSAFE_componentWillReceiveProps .
The main difference between the two is:
state
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 prevProps
and prevState
.
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 componentDidUpdate
.
state
?The main difference here is:
componentWillReceiveProps
will update state synchronously componentDidUpdate
will 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With