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

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

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