componentWillReceiveProps
is required if you want to update the state values with new props values, this method will get called whenever any change happens to props values.
In your case why you need this componentWillReceiveProps method?
Because you are storing the props values in state variable, and using it like this:
this.state.KeyName
That’s why you need componentWillReceiveProps
lifecycle method to update the state value with new props value, only props values of component will get updated but automatically state will not get updated. If you do not update the state then this.state
will always have the initial data.
componentWillReceiveProps
will be not required if you do not store the props values in state and directly use:
this.props.keyName
Now react will always use updated props values inside render method, and if any change happen to props, it will re-render the component with new props.
As per DOC:
componentWillReceiveProps() is invoked before a mounted component receives new props. If you need to update the state in response to prop changes (for example, to reset it), you may compare this.props and nextProps and perform state transitions using this.setState() in this method.
React doesn’t call componentWillReceiveProps with initial props during mounting. It only calls this method if some of component’s props may update.
Suggestion:
Do not store the props values in state, directly use this.props
and create the ui components.