which component method can we use to set the state based the prop value changes? i know we can use componentWillRecieveProps but it is going to be deprecated so which can we use as a alternative to componentWillRecieveProps. also please post a simple code example if possible
4 Answers
In class components you can now use static getDerivedStateFromProps(props, state)
A example from the docs:
static getDerivedStateFromProps(props, state) {
// Any time the current user changes,
// Reset any parts of state that are tied to that user.
// In this simple example, that's just the email.
if (props.userID !== state.prevPropsUserID) {
return {
prevPropsUserID: props.userID,
email: props.defaultEmail
};
}
return null;
}
You can use the componentDidUpdate
method
componentDidUpdate(prevProps, prevState) {
if (prevProps.data !== this.props.data) {
//do something
}
}
-
1Correct, but when changing the state based on prop changes, maybe
shouldComponentUpdate
would be a better choice, that way you could skip the prop rerender and only use the statechange rerender. Sep 18, 2019 at 10:49 -
Good point, I didn't read OPs question carefully enough and didn't see that he wanted to change the state based on prop changes. Thanks. Sep 18, 2019 at 10:51
getDerivedStateFromProps
It was introduced in react 16.3 to replace :
componentWillReceiveProps
which will be deprecated in react 17 and now become
UNSAFE_componentWillReceiveProps
static getDerivedStateFromProps(nextProps, prevState) {
if(nextProps.someValue!==prevState.someValue){
return { someState: nextProps.someValue};
} else return null;
}
This lifecycle method take the previous and the next props as an input and return the derived state.
This method is static so you cant use this
inside.
For further information read Replacing ‘componentWillReceiveProps’ with ‘getDerivedStateFromProps’
static getDerivedStateFromProps(nextProps, prevState) {
if (nextProps.total !== prevState.total) {
//your code
}
}