I'm new to React and I'm going through the lifecycles of React, however I'm little bit confused with the use of componentWillReceiveProps
.
Can anyone explain me in which case it should be used.
Thanks.
This method is called when props are passed to the Component. can be used to update the internal state of the component from newly received props.
Please refer to this link for better understanding. https://developmentarc.gitbooks.io/react-indepth/content/life_cycle/update/component_will_receive_props.html
however, it is deprecated in React 16.
So, componentWillReceiveProps is invoked everytime your component receives new props, it's used to update the state of the component.
So for example:
export default class ExampleComponent extends Component {
constructor(props) {
super(props);
state = {
stateExample: this.props,
}
}
componentWillReceiveProps(nextProps) {
if (this.props !== nextProps) {
this.setState(nextProps)
}
}
}
Please note that componentWillReceiveProps is deprecated since react 16. You should start using getDerivedStateFromProps. On the same example above, it would be like this:
static getDerivedStateFromProps(nextProps, prevState) {
if(nextProps.stateExample !== prevState.stateExample) {
return { stateExample: nextProps.stateExample }
} else return null;
}
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