From the official tutorial:
componentWillUnmount()
is invoked immediately before a component is unmounted and destroyed. Perform any necessary cleanup in this method, such as invalidating timers, canceling network requests, or cleaning up any DOM elements that were created incomponentDidMount
I understood "invalidating timers". fetch
can be aborted with AbortController
. But I don't understand "cleaning up any DOM elements that were created in componentDidMount
", can I see examples for that case?
ReactJS – componentWillUnmount() MethodThis method is called during the unmounting phase of the React Lifecycle, i.e., before the component is destroyed or unmounted from the DOM tree. This method is majorly used to cancel all the subscriptions that were previously created in the componentWillMount method.
The componentWillUnmount() method allows us to execute the React code when the component gets destroyed or unmounted from the DOM (Document Object Model). This method is called during the Unmounting phase of the React Life-cycle i.e before the component gets unmounted.
To understand how we can use componentWillUnmount, first we need to look at how the component manages mounting with useEffect. If we pass an empty array as the second argument, it tells useEffect to fire on component load. This is the only time it will fire.
How to use componentWillUnmount with react hooks? For this task, we will useEffect hook provided by React JS and call our subscription for event or API inside useEffect and do the cleanup of that particular task inside useEffect hook itself.
If the network request sending library supports aborting the ongoing network request call, you can definitely call that in componentWillUnmount
method.
However in relation to cleaning up of DOM
elements is of concern. I will give a couple of examples, based on my current experience.
First one is -
import React, { Component } from 'react'; export default class SideMenu extends Component { constructor(props) { super(props); this.state = { }; this.openMenu = this.openMenu.bind(this); this.closeMenu = this.closeMenu.bind(this); } componentDidMount() { document.addEventListener("click", this.closeMenu); } componentWillUnmount() { document.removeEventListener("click", this.closeMenu); } openMenu() { } closeMenu() { } render() { return ( <div> <a href = "javascript:void(0)" className = "closebtn" onClick = {this.closeMenu} > × </a> <div> Some other structure </div> </div> ); } }
Here I am removing the click event listener which I added when the component mounted.
Second one is -
import React from 'react'; import { Component } from 'react'; import ReactDom from 'react-dom'; import d3Chart from './d3charts'; export default class Chart extends Component { static propTypes = { data: React.PropTypes.array, domain: React.PropTypes.object }; constructor(props){ super(props); } componentDidMount(){ let el = ReactDom.findDOMNode(this); d3Chart.create(el, { width: '100%', height: '300px' }, this.getChartState()); } componentDidUpdate() { let el = ReactDom.findDOMNode(this); d3Chart.update(el, this.getChartState()); } getChartState() { return { data: this.props.data, domain: this.props.domain } } componentWillUnmount() { let el = ReactDom.findDOMNode(this); d3Chart.destroy(el); } render() { return ( <div className="Chart"> </div> ); } }
Here I am trying to integrate d3.js
with react into componentWillUnmount
; I am removing the chart element from the DOM.
Apart from that I have used componentWillUnmount
for cleaning up bootstrap modals after opening.
I am sure there are tons of other use cases out there, but these are the cases where I have used componentWillUnMount
. I hope it helps you.
In this simple example (example taken from React Docs) I am using it for clearing interval of a Clock component. For example in your page you have 2 tabs, one of them is showing User Info
and second tab is User Schedule
which shows a live clock over there. Once you switch to User Schedule
tab, componentDidMount
will be called to set the timer. And once you switch back to User Info
, there is no need to keep this interval hook and you can write your unbind/unsubscribe logic in componentWillUnmount
event.
import React from "react"; export default class Clock extends React.Component { constructor(props) { console.log("Clock", "constructor"); super(props); this.state = { date: new Date() }; } tick() { this.setState({ date: new Date() }); } // These methods are called "lifecycle hooks". componentDidMount() { console.log("Clock", "componentDidMount"); this.timerID = setInterval(() => { this.tick(); }, 1000); } // These methods are called "lifecycle hooks". componentWillUnmount() { console.log("Clock", "componentWillUnmount"); clearInterval(this.timerID); } render() { return ( <div>It is {this.state.date.toLocaleTimeString()}.</div> ); } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With