componentWillUnmount() in ReactJS

componentWillUnmount() method is invoked right before component is removed from DOM and destroyed.

componentWillUnmount() is the only method of unmounting phase of component.

Why componentWillUnmount() should be used?

componentWillUnmount() method is mostly used for cleanup tasks like below.

  • Cancelling network request made by component
  • Clear timers that may be used in component
  • Unsubscribe events or some other things which may be subscribed in componentDidMount() lifecycle method.

Points to remember while using componentWillUnmount()

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

Conclusion

In this section, we learned about componentWillUnmount() method and for what it can be used.
In upcoming sections, we will learn about legacy methods but currently are in use.
In the next section, you will learn about componentWillMount() method of ReactJS component.