componentWillUpdate() in ReactJS

componentWillUpdate(nextProps, nextState) method is invoked just before render() lifecycle method when new state or props is received.

componentWillUpdate() 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 state or props is updated, this method is called.

Why componentWillUpdate() should be used?

componentWillUpdate() is mostly used to fetch data. But for that, you can replace it with componentDidUpdate() lifecycle method.

If you are using componentWillUpdate() for reading from DOM ( e.g. getting scroll position ), you can replace it with getSnapshotBeforeUpdate() lifecycle method.

Points to remember while using componentWillUpdate()

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

  • componentWillUpdate() will not be invoked in mounting phase.
  • You can not call anything like setState() that could update the component in componentWillUpdate() method.
  • If you need to do some side-effect work like fetching data or third party library, componentWillUpdate() is not the best place for that. You can do that in componentDidUpdate().

Conclusion

In this section, we learned about componentWillUpdate() method and for what it can be used.
In the next section, you will learn about events in ReactJS component.