FAC6 / facfaq

Raise your open-ended questions (tech-related) on this repo!

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

REACT - Do we need to detach event handlers in componentWillUnmount?

mantagen opened this issue · comments

commented

For instance, in a React component, if an event handler is attached to the window on render (is that bad practise in itself?/ always avoidable) , should it it detached in the componentWillUnmount method?

@mantagen what problem are you trying to solve...?

commented

@nelsonic I'm not trying to solve a problem, I was asking precautionarily so as to avoid a potential problem.

From what I've read here, event listeners which you attach to elements not in your component (eg to the window) will remain after your component unmounts unless you make it happen in componentWillUnmount.

So the answer to my (perhaps poorly phrased) question is yes, because react doesn't do that clean up for you.

So far the clean-up operations I've found which might be handy in componentWillUnmount are:

Clearing setTimeout
Clearing setInterval
Stopping requestAnimationFrame
Removing or unbinding event listeners

What else is there? (maybe this should be a separate question)

commented

I'm unclear what event handlers you're trying to remove. Attaching event handlers to the window onComponentMount does not seem particularly 'react'-y ... On the other hand, React itself only has one top-level event handler (I believe on the document, rather than the window) and uses event delegation to work out where the relevant events should be targeted.

That said if you are mutating some state on a global (like, for example, a timeout or an interval (RAF, I think, is a little bit more complicated)), you probably will want to clean that up at some point.

This can normally be managed within your top-level react component. I've not heard of a use case for dynamically mounting and unmounting your whole react app (which is what unmountAtNode provides, as near as I can tell)

commented

Agreed it wouldn't be that self contained (so not really in the spirit of react components per se) to attach an event handler to the window on render etc. But it might be that someone did want to do it for some niche reason.
If they were to do it, and wanted the event handler to no longer be there after the component was unmounted, would react clean it up for them by default, or would they need to do it manually?
The answer is that they would need to do it manually.
Sorry, the question wasn't particularly practical it was more borne of a curiosity as to the nature of react's unmounting process.