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

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

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