componentWillReceiveProps() in ReactJS
componentWillReceiveProps(nextProps) method is invoked before a mounted component gets new
componentWillReceiveProps() is the the method of updating phase of component, So it is not called the first time when component is not added to DOM. When component is mounted and receives new
props, this method is called.
In React Version => 16.3, all the legacy method have UNSAFE_ before its name. That means if you want to use those ( at your risk ), use with name
Use rename-unsafe-lifecycles to automatically add UNSAFE_ prefix to
Why componentWillReceiveProps() should be used?
componentWillReceiveProps(nextProps) method is used when you need to update the
state in response to
componentWillReceiveProps(nextProps) method provides updated
props object as parameter. You can compare and update
Points to remember while using componentWillReceiveProps()
There are many points that you should remember while using
componentWillReceiveProps()is called when
propsis updated. But when parent component re-renders the child component,
componentWillReceivePropsof child component will be called even if there is no change in
propsof child component. So please add some comparision for current
componentWillReceiveProps()will not be invoked in mounting phase.
If you need to do some side-effect work like fetching data or third party library,
componentWillReceiveProps()is not the best place for that. You can do that in componentDidUpdate() ( or componentDidMount for initial mounting ).
In this section, we learned about
componentWillReceiveProps() method and for what it can be used.
In the next section, you will learn about componentWillUpdate() method of ReactJS component.