Search code examples
reactjsaddeventlisteneruse-effect

scroll eventlistener is interupting the scrolling event it triggers


I have a event listener triggering a auto scroll event. however the auto scroll is triggering the event listener again which messes up the transition. How can I temporarily disable the listener while the auto scroll happens? Here is the listener:

    useEffect(() => {
        window.addEventListener("scroll", () => {
            scroll.scrollToBottom();//animated scroll to bottom of page
          });
    }, [])

Solution

  • Try creating and removing the event listener:

    const scrollToMainContent = () => {
            window.removeEventListener('scroll', scrollToMainContent);
            scroll.scrollToBottom();
    }
    useEffect(() => {
            window.addEventListener("scroll", scrollToMainContent);
    }, [])