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

203
Views
Window.scroll only working once (React.js)

I'm making a simple React component to remember where you are on the page and place you there when returning.

Here's the code:

function ScrollCache() {
  window.scroll(0, parseInt(localStorage['scroll']));
  document.addEventListener('scroll', function (e) {
    if (window.scrollY != 0) {
      localStorage['scroll'] = window.scrollY.toString();
    }
  })
  return (<></>)
}

Basically, it caches the last known scroll position, and uses window.scroll(x, y) to scroll to that position. I have verified that localStorage is working as intended with a console.log immediately before the window.scroll. I've also just tried a static 100 for the y coordinate. No matter what, it only scrolls once at reload and then never again when I'm navigating around.

I'm using React Router to go between web pages. Any help is appreciated

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

0

You don't need to add the scroll event listener every time you want to cache the scroll.

Instead, try this:

const [scrollPosition, setScrollPosition] = useState(0);

useEffect(() => {
    window.addEventListener("scroll", handleScroll, {
        passive: true
    });
    return () => {
        window.removeEventListener("scroll", handleScroll);
    };
}, [scrollPosition]);

useEffect(() => {
   localStorage['scroll'] = scrollPosition.toString();
}, [scrollPosition);

const handleScroll = () => {
    const position = window.pageYOffset;
    setScrollPosition(position);
};
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!