window.onpopstate - do I need to remove this event handler?

reactjs browser event-handling react-router

3592 观看


1524 作者的声誉

I'm using window.onpopstate event handler to listen for back and forward browser button events. My code looks something like this:

componentDidMount() {
    window.onpopstate = this.onBackOrForwardButtonEvent;

onBackOrForwardButtonEvent = (e) => {
    e.preventDefault();'back or forward button pressed');
    if (this.props.route.path !== '/app') {
       // ... do something

My question is: Do I need to remove this event listener - perhaps in componentWillUnmount?

something like:

componentWillUnmount() {
    window.removeEventListener('onpopstate', this.onBackOrForwardButtonEvent, false)

I've seen examples using onPopState like I have above but never with removing the listener when the component unmounts.


作者: user2456977 的来源 发布者: 2017 年 12 月 27 日

回应 (1)


18506 作者的声誉


I think you are ok not worrying about the removal of the attached event.

Your example is interesting because the event is attached to the window rather than a dom element. In this case, I think you are fine not removing any events because the event exists natively - each time your component mounts, it reassigns a handler to the already attached event.

Assigning the handler to a no-op might be more reasonable in the event of the component unmounting if you want to ensure the event doesnt fire after a components removal.

componentDidUnmount() {
  window.onpopstate = () => {}

For dom event listeners, this is different.

It is common for react apps to act like single page apps, where new elements are phased in (mounted) via the router and client side navigation, and subsequently unmounted as a user explores the page.

When an element is removed from the DOM (or unmounted), it is best practice to remove any event listeners attached to it.

If you don't remove the event listener, there is a chance the event will continue to use up memory unnecessarily.

Its also entirely possible that modern browsers handle this for you via garbage collection but why bother yourself knowing which browser does what when you can take the extra step to be careful.

作者: lfender6445 发布者: 27.12.2017 07:20