componentWillUpdate() in ReactJS
componentWillUpdate(nextProps, nextState) method is invoked just before render() lifecycle method when new
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
props is updated, 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 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()will not be invoked in mounting phase.
You can not call anything like setState() that could update the component in
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().
componentWillUpdate() method will not be invoked if shouldComponentUpdate() method returns
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.