Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

206
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda