32

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.

  • I don't think getDerivedStateFromProps is asynchronous. https://github.com/facebook/react/issues/13541 – Rob OT Nov 02 '18 at 10:34

2 Answers2

46

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.

Bhojendra Rauniyar
  • 83,432
  • 35
  • 168
  • 231
7

My understanding is that if the componentWillReceiveProps() method is being invoked then some properties of the component has been changed and that component should be informed and potentially re-rendered again.

Having ajax call inside of the componentWillReceiveProps() might break that flow.

My gut feeling is that we are gently guided to make ajax calls outside of the components and pass all the results of those ajax calls through properties. It makes your components very clean and testable.

Grzegorz Gralak
  • 717
  • 8
  • 7