1

I am using componentWillReceiveProps in many places in my application. Now, I have to replace them with either getDerivedStateFromProps() or componentDidUpdate(). First I thought of using getDerivedStateFromProps as it s alternative of componentWillReceiveProps as suggested react-native docs. But some people are highly recommending not to use this method, Instead suggesting to use componentDidUpdate. But for my requirement all new props must be set with the state before render. getDerivedStateFromProps is the best place to do so.

Hence, which one to use between getDerivedStateFromProps and componentDidUpdate?

ThinkAndCode
  • 1,319
  • 3
  • 29
  • 60
  • as a recommendation, you may wish to consider using hooks and functional components unless your components/application is heavily using class components already – Denis Tsoi Aug 11 '20 at 05:33

1 Answers1

0

From the React docs

https://reactjs.org/docs/react-component.html#static-getderivedstatefromprops

getDerivedStateFromProps is invoked right before calling the render method, both on the initial mount and on subsequent updates. It should return an object to update the state, or null to update nothing.

Deriving state leads to verbose code and makes your components difficult to think about.

Make sure you’re familiar with simpler alternatives:

  • If you need to perform a side effect (for example, data fetching or an animation) in response to a change in props, use componentDidUpdate lifecycle instead.
  • If you want to re-compute some data only when a prop changes, use a memoization helper instead.
  • If you want to “reset” some state when a prop changes, consider either making a component fully controlled or fully uncontrolled with a key instead.
Denis Tsoi
  • 9,428
  • 8
  • 37
  • 56