As read in this React Github issue I see more and more that
the cost of
render()
is relatively small
In React 1
So Dan Abramov answered on Twitter and it seems like there are 2 reasons why you should use getDerivedStateFromProps
instead of componentDidUpdate
+ setState
:
setState in componentDidUpdate causes an extra render (not directly perceptible to user but it slows down your app). And you render method can’t assume the state is ready (because it won’t be the first time).
getDerivedStateFromProps
is called before rendering on init, you can initialise your state in this function instead of having a constructor to do so.
Currently you had to have a constructor or componentWillMount
to init your state before initial rendering.getDerivedStateFromProps
is actually replacement for componentWillReceiveProps
and componentDidMount
is not going to be deprecated.
I'm pretty sure it was the community that decided to make a static method with that name.
The reason for this change is that componentWillReceiveProps was one of the methods that led to confusion and further to some memory leaks in user applications:
Many of these issues are exacerbated by a subset of the component lifecycles (componentWillMount, componentWillReceiveProps, and componentWillUpdate). These also happen to be the lifecycles that cause the most confusion within the React community. For these reasons, we are going to deprecate those methods in favor of better alternatives.
Here's the Dan Abramov tweet that also makes this more clear:
However, this means that we’ll part our ways with componentWillReceiveProps() in 17. We think getDerivedStateFromProps() does the same job better and is less confusing. It also happens that cWRP() really messes up our plans for data fetching features that might be in pipeline.