React introduced new static method getDerivedStateFromProps(props, state) which is called before every render method, but why? Calling it after prop change makes se
The way getDerivedStateFromProps hook works whenever the new props, setState, and forceUpdate is being received.
In the version of 16.3, React is not affecting getDerivedStateFromProps whenever the setState is being used. But they improved it in the version starting with 16.4, so whenever the setState is being called the getDerivedStateFromProps is being hooked.
Here's extracted image from React lifecycle diagram:
So, it's up to you when to hook the getDerivedStateFromProps by checking props and states properly. Here's an example:
static getDerivedStateFromProps (props, state) {
// check your condition when it should run?
if(props.currentMonth != state.currentMonth) {
return {
currentMonth: state.currentMonth
}
}
// otherwise, don't do anything
else {
return null
}
}