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

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

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 Relatório

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 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