componentWillReceiveProps() in ReactJS

componentWillReceiveProps(nextProps) method is invoked before a mounted component gets new props.

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.

Why componentWillReceiveProps() should be used?

componentWillReceiveProps(nextProps) method is used when you need to update the state in response to prop changes.

componentWillReceiveProps(nextProps) method provides updated props object as parameter. You can compare and update state accordingly.

Points to remember while using componentWillReceiveProps()

There are many points that you should remember while using componentWillReceiveProps() method.

  • componentWillReceiveProps() is called when props is updated. But when parent component re-renders the child component, componentWillReceiveProps of child component will be called even if there is no change in props of child component. So please add some comparision for current props and updated props.
  • 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 ).

Conclusion

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.