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

124
Views
Live vertical viewport tracking not working in React

I want to get the current y position in de document to change the ui at certain moments. The code I use atm doesn't work and I don't get why.

const [verticalPosition, setVerticalPosition] = useState()

useEffect(() => {
    setVerticalPosition(window.scrollY)
}, [window.scrollY])

useEffect(() => {
    console.log(verticalPosition)
}, [verticalPosition])

I've searched for alternatives and found the most complex libraries to do something just that easy. So I would want to make it work this way. Could someone tell me how this could get working?

Thanks in advance

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

You need to add an event listener to the document.scroll event like so:

const [verticalPosition, setVerticalPosition] = useState()

useEffect(() => {
    const onScroll = ()=>{
        setVerticalPosition(window.scrollY);
    }
    document.addEventListener('scroll', onScroll);
    return ()=>document.removeEventListener('scroll', onScroll); // cleanup function runs when component is unmounted
}, []); // empty dependency array so it only runs on mount

Pro tip

If you need this behavior in multiple components, this is trivial to abstract into a custom hook:

// hooks/useScrollY.js
const useScrollY = ()=>{
  const [verticalPosition, setVerticalPosition] = useState()

  useEffect(() => {
      const onScroll = ()=>{
          setVerticalPosition(window.scrollY);
      }
      document.addEventListener('scroll', onScroll);
      return ()=>document.removeEventListener('scroll', onScroll);
  }, []); 
  return verticalPosition;
}
export default useScrollY;

// how to use:
import useScrollY from "../hooks/useScrollY"

const MyComponent = ()=>{
  const scrollY = useScrollY();
  // do something with scrollY
  return (
    //...
  );
}
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!