Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

189
Vistas
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 Respuestas
Responde la pregunta

0

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

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda