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?
Simple solution is as follows:
When creating
Components
with React, not every library integrates well with it's philosophy of wanting to manage the DOM.An example of this would be using a graphing library like c3.
c3
expects to be given a DOM node and will create / manage it's own markup away from React. In this case you should manage cleaning up any elements created by this library when your component is removed from the DOM.Here React creates a single
div
as a placeholder forc3
to add it's content. This process is kicked off in thecomponentDidMount
lifecycle hook, and cleaned up again incomponentWillUnmount
.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 -
Here I am removing the click event listener which I added when the component mounted.
Second one is -
Here I am trying to integrate
d3.js
with react intocomponentWillUnmount
; 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 isUser Schedule
which shows a live clock over there. Once you switch toUser Schedule
tab,componentDidMount
will be called to set the timer. And once you switch back toUser Info
, there is no need to keep this interval hook and you can write your unbind/unsubscribe logic incomponentWillUnmount
event.