React, componentWillMount() lifeCycle Hook

I was trying to pass props both in App component (The root Component) and then to Header component from App itself.

I have used Life Cycle Hooks upto componentWillReceiveProps() in both App and Header Component.

componentWillMount(), render(), componentDidMount() are getting executed in both the Components in an expected order.

However, componentWillReceiveProps() is not executed at all even on passing props. This is a unExpected behaviour, since componentWillMount() was executed normally!

I shall be extremely thankful to know why is this happening ! Thank you :)

Kindly check the code sample from the below link:

https://codesandbox.io/s/mjj0q75yoj

Kindly please to the image for more clarity about the issue:

componentWillReceiveProps() not being invoked

2 answers

  • answered 2018-11-08 08:36 Keilath

    As stated in the official documentation (see https://reactjs.org/docs/react-component.html) the

     componentWillReceiveProps()
    

    lifecycle method is deprecated and should be avoided.

    The reason why it is never called is that, to help user avoid it, React developers renamed it

     UNSAFE_componentWillReceiveProps()
    

    You should however avoid it, since they plan to deprecate that method

  • answered 2018-11-08 08:50 Alex

    I don't see why you expect your components to be updated (who pass new props them?), but generally you should use componentDidUpdate(prevProps, prevState)

    Also consider managing the state by static getDerivedStateFromProps(props, state), i.e.:

    static getDerivedStateFromProps(props, state){
      // just return the state
      return {
        isLoading: false,
        money: props.money
      }
    }
    

    - it's executed on init + on updates.