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

270
Views
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 answers
Answer question

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 Report

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