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

272
Vistas
Logging scroll position on scroll using React hooks

so I've been trying to simply get my event listener for a component to work and update on scroll. I've found this post: Get scroll position with Reactjs and I've tried the second answer (because I'm working mostly with hooks and I want my code to be consistent.) So I have this code within my component:

const [scrollPosition, setScrollPosition] = useState(0);
const handleScroll = () => {
    const position = window.scrollY;
    console.log(position);
    setScrollPosition(position);
};

useEffect(() => {
    window.addEventListener('scroll', handleScroll, { passive: true });

    return () => {
        window.removeEventListener('scroll', handleScroll);
    };
}, [scrollPosition]);

The code logs nothing to the console and whenever I try to use scroll position the value is always 0. Am I doing something wrong? Any help would be greatly appreciated!

about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

So I finally understand why the code wasn't working. The page I was wanting to scroll was wrapped within a div. The div took up the whole page and has multiple sections. I thought that the div was simply expanding the page and that the window was still being scrolled. It turns out that I was actually scrolling within the div and not the window. So the following is what ended up working:

const scrollEvent = (e) => { 
    console.log(e.target.scrollTop)
  }
...
<div onScroll={scrollEvent}>
   ...
</div>

I'm not sure if this is the most optimal or anything but at least it gives me the scroll position I wanted. Thank you everyone who answered!

about 4 years ago · Juan Pablo Isaza Denunciar

0

You are giving the dependency to the useEffect. The useEffect will only be executed once the scrollPosition is changed.

And it will never change in your code, since the useEffect is not executed. It is mutually dependent.

Try removing the scrollPosition in the useEffect dependency.

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