P
P
ParaBellum5772019-04-04 14:48:43
React
ParaBellum577, 2019-04-04 14:48:43

How to remove a listener?

There is a "fast up" button that only appears when the page is swiped more than 500px.
Everything works, but there is an unpleasant warning that indicates a memory leak. Due to the constant updating of the state in componentDidMount .
How to fix it correctly?
Here is the code:

isFastUpVisible = () => {
    if (window.pageYOffset > 500) {
      this.setState({fastUpHidden: false})
    } else {
      this.setState({fastUpHidden: true})
    }
  }

  goToTop = () => {
    let timer;
       if(window.pageYOffset > 0) {
         window.scrollTo(0, window.pageYOffset - 400);
         timer = setTimeout(this.goToTop, 20)
       } else {
         clearTimeout(timer);
         window.scrollTo(0,0);
     }
   }

  componentDidMount() {
    window.addEventListener("scroll", this.isFastUpVisible);
   }

Here is the warning:5ca5ef4ac5a82866315678.png

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Anton Spirin, 2019-04-04
@ParaBellum577

componentWillUnmount() {
  window.removeEventListener('scroll', this.isFastUpVisible);
  clearTimeout(this.timeout);
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question