Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

184
Views
Why is the event listener removed after Next.js route change?

I'm using the following useEffect in a component to control active state on an anchor side navigation for the page.

const [activeIndex, setActiveIndex] = useState(0);

useEffect(() => {
    const handleScroll = (e: Event) => {
        var index = nearestIndex(
            window.scrollY,
            Anchors,
            0,
            Anchors.length - 1
        );

        setActiveIndex(index);
    }

    document.addEventListener("scroll", handleScroll);
    return () => {
        document.removeEventListener("scroll", handleScroll);
    }
}, [Anchors]);

When I navigate to another page using next/link the scroll event listener is firing and then being removed. This is causing an error inside nearestIndex because the refs inside Anchors are now null.

EDIT: Component/Page Flow Explanation

  1. Navigate to Page 1 - displays Anchor Links component with code above
  2. Click anchor link - page scrolls down a bit
  3. Navigate to Page 2 - does not contain Anchor Links component, scroll event listener fires throwing an error, listener is then removed
  4. Navigate to Page 3 - does not contain Anchor Links component, no error because the scroll event listener is no longer registered
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Because return in useEffect works on component unmounting. Please read documentation of useEffect

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!