I read through https://reactjs.org/blog/2018/03/27/update-on-async-rendering.html#fetching-external-data-when-props-change . I am still not able to understand why did they have to deprecate componentWillReceiveProps.
What was the harm in making an ajax call inside componentWillReceiveProps? Once ajax call returns the value , I update the state thereby rerendering the component.
The useEffect hook is also the equivalent of the componentWillReceiveProps or componentDidUpdate hooks. All we have to do is to pass in an array with the value that we want to watch for changes.
ReactJS – componentWillReceiveProps() Method This method is used during the updating phase of the React lifecycle. This function is generally called if the props passed to the component change. It is used to update the state in response with the new received props.
The reason for this decision is twofold: All three methods are frequently use incorrectly and there are better alternatives. When asynchronous rendering is implemented in React, misuse of these will be problematic, and the interrupting behavior of error handling could result in memory leaks.
There are a few life cycle methods that have been deprecated and renamed in React 17. We don't need to use these anymore— getDerivedStateFromProps and getSnapshotBeforeUpdate essentially replaced them.
componentWillReceiveProps
is a synchronous hook. Calling asynchronous function like data fetching inside this hook will need to render in between when the new props are set and when data has finished loading.
But the getDerivedStateFromProps
is an asynchronous hook won't require any additional render. Thus, componentWillReceiveProps
is being deprecated in favor of the following reason:
Which won't give you unnecessary renders. Note that getDerivedStateFromProps
is used only in rare case though. So, I suggest you to use componentDidUpdate
hook as far as possible.
The similar things happen when comparing componentWillMount and componentDidMount. Use componentDidMount whenever you need operate async operation and forget componentWillMount at all condition. More explanation about componentDidMount is here in my another post.
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