Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why is componentWillReceiveProps deprecated?

Tags:

reactjs

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.

like image 366
Shrihari Balasubramani Avatar asked Aug 23 '18 08:08

Shrihari Balasubramani


People also ask

What is the replacement for componentWillReceiveProps?

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.

When should I use componentWillReceiveProps?

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.

Why is componentWillMount deprecated?

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.

Is getDerivedStateFromProps deprecated?

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.


1 Answers

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:

  1. Use getDerivedStateFromProps
  2. Or, use componentDidUpdate

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.

like image 80
Bhojendra Rauniyar Avatar answered Sep 17 '22 14:09

Bhojendra Rauniyar