Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove event listener manually react hooks

I have a scroll event listener and I want to remove it based on page URL, how can I handle it using in a hook component?

 useEffect(() => {
    function handleScrollEvent() {
      if (window.scrollY > 100) {
        setHeaderIsVisible(true);
      } else {
        setHeaderIsVisible(false);
      }
    }
    if (props.location.pathname === "/") {

      window.addEventListener("scroll", handleScrollEvent, true);
    } else {
      window.removeEventListener("scroll", handleScrollEvent, true);
    }
  }, [props.location.pathname]);

Where I should define the handleScrollEvent to remove it from listener?

like image 708
Hadi Ranjbar Avatar asked Jul 30 '19 14:07

Hadi Ranjbar


People also ask

Do you need to remove event listeners?

TLDR; Always remove event listeners when you don't plan on using them any longer.

How do I delete an onClick event in React?

We set an event handler to the onClick event of the button, so when the button is clicked, the handler function will be called. In the handler function, we use the setState function for the visibility state to update the state. const removeElement = () => { setVisible((prev) => ! prev); };

What is ComponentDidUpdate in React hooks?

What is componentDidUpdate? ComponentDidUpdate is a React component lifecycle method invoked immediately after a component's updates are flushed to the DOM. This is one of the most used built-in methods, which is not called for the initial render nor applicable to your functional details.


1 Answers

What you need to do is every time you add it, you also remove it.

When props.location.pathname changes, it will remove the event listener.

useEffect(() => {
    if (props.location.pathname === "/") {  
      function handleScrollEvent() {
        if (window.scrollY > 100) {
          setHeaderIsVisible(true);
        } else {
          setHeaderIsVisible(false);
        }
      }

      window.addEventListener("scroll", handleScrollEvent, true);  
      // every time you add it, you also remove it when props.location.pathname changes
      return () => {
           window.removeEventListener("scroll", handleScrollEvent, true);
      }
    }
  }, [props.location.pathname]);
like image 104
Vencovsky Avatar answered Oct 19 '22 21:10

Vencovsky