As read in this React Github issue I see more and more that
the cost of
render()
is relatively small
In React 16.3, I'm wondering why one would use the new getDerivedStateFromProps instead of componentDidUpdate?
Imagine this example:
getDerivedStateFromProps(nextProps, prevState) { if (!prevState.isModalOpen && nextProps.isReady) { return { isModalOpen: true }; } }
versus
componentDidUpdate(prevProps, prevState) { if (!prevState.isModalOpen && this.props.isReady) { this.setState({ isModalOpen: true }); } }
The later seems simpler just because it's using only existing API and looks just like what we used to do in componentWillReceiveProps so I don't see why users would go for getDerivedStateFromProps? What's the benefit?
Thanks!
The getDerivedStateFromProps() method is used when the state of a component depends on changes of props. getDerivedStateFromProps(props, state) is a static method that is called just before render() method in both mounting and updating phase in React. It takes updated props and the current state as arguments.
So essentially, useEffect react to changes in dependency list. They have replaced componentDidMount, componentDidUpdate, componentWillUnmount and componentWillReceiveProps in class based react components. It's very common to react to changes in props values or state values over the lifetime of a component.
getDerivedStateFromProps is a new API that has been introduced in order for it to be extensible when Async rendering as a feature is released. According to Dan Abramov in a tweet , This method is chosen to be static to help ensure purity which is important because it fires during interruptible phase.
The componentDidUpdate() method allows us to execute the React code when the component is updated. All the network requests that are to be made when the props passed to the component changes are coded here.
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.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