Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

187
Visualizações
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 Respostas
Responde à pergunta

0

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

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda