1

If I attached event listener to a component, do I need to explicitly to remove it when it's unmounted?

For e.g.

componentRef = React.createRef();
    handleWheel = (e) => {
      e.preventDefault();
    }
    componentDidMount() {
      if (this.componentRef.current) {
        this.componentRef.current.addEventListener('wheel', this.handleWheel);
      }
    }
    componentWillUnmount() {
      if (this.componentRef.current) {
        this.componentRef.current.removeEventListener('wheel', this.handleWheel);
      }
    }
    render() {
      <Container ref={this.componentRef}>...</Container>
    }

So I wonder if componentWillUnmount is required in this case

Yuriy Chachora
  • 739
  • 6
  • 18
  • 1
    The duplicate states that yes, you should, because old browsers like IE6 and IE7 will not remove event handlers correctly when the element is removed from the DOM. I think in this day and age, no-one in their right mind supports those browsers anymore, so I would vote for “no, you don't have to remove the event handler on component unmount” – Patrick Hund Aug 17 '19 at 09:22
  • Yes, it is duplicate. Couldn't find another answer myself – Yuriy Chachora Aug 17 '19 at 09:38

0 Answers0