I've read the documentation on reactjs.org regarding getDerivedStateFromProps. I've seen the use cases. And I understand why to use it.
But I cannot figure out how it deals with the return value. Hence my question, when it does return... where does it go?
It doesn't setState because it does not have access to this.
To set state, requires using componentDidUpdate and looking for changes, then setting state.
Assume the following code:
public static getDerivedStateFromProps: IArrowFunction = (nextProps: IMyContainerProps, prevState: IMyContainerState) => {
if (nextProps.havingFun !== prevState.havingFun) {
console.log('[MyContainer.tsx] getDerivedStateFromProps :::::CHANGED::::::', nextProps, prevState);
return { havingFun: nextProps.havingFun };
} else { return null; }
}
So what does React do with that return ^?
I could then setState on componentDidMount. But this does not appear to have anything to do with getDerivedStateFromProps. Additionally this lifecycle method triggers every time. And it forces a re-render.
public componentDidUpdate(prevProps: IMyContainerProps, prevState: IMyContainerState): void {
if (prevState.havingFun !== this.props.havingFun) {
console.log('[MyContainer.tsx] componentDidUpdate *******CHANGED******', prevState, prevProps, this.props);
this.setState({ havingFun: this.props.havingFun });
}
}
At what point does the return from getDerivedStateFromProps come into play?
UPDATED: this lifecycle method will actually update state if properly configured as above. You do not need an additional method to setState
The return value is similar in concept like setState:
return { havingFun: nextProps.havingFun };
Where you can assume havingFun
a state property and the value nextProps.havingFun
is updated value.
When you use return null
it means you are not doing anything with the state.
Note: getDerivedStateFromProps is really different concept than setState though I have tried here to explain it the way only.
You should read the docs for more detail:
getDerivedStateFromProps is invoked right before calling the render method, both on the initial mount and on subsequent updates. It should return an object to update the state, or null to update nothing.