Skip to content

Instantly share code, notes, and snippets.

@gambinish
Forked from joshuacerbito/useScroll.js
Created April 13, 2019 06:37
Show Gist options
  • Save gambinish/1fc2194fc4c2cf59d5cbda2220f95dc1 to your computer and use it in GitHub Desktop.
Save gambinish/1fc2194fc4c2cf59d5cbda2220f95dc1 to your computer and use it in GitHub Desktop.
Custom React hook for listening to scroll events
/**
* useScroll React custom hook
* Usage:
* const { scrollX, scrollY, scrollDirection } = useScroll();
*/
import { useState, useEffect } from "react";
export function useScroll() {
const [lastScrollTop, setLastScrollTop] = useState(0);
const [bodyOffset, setBodyOffset] = useState(document.body.getBoundingClientRect());
const [scrollY, setScrollYX] = useState(bodyOffset.top);
const [scrollX, setScrollX] = useState(bodyOffset.left);
const [scrollDirection, setScrollDirection] = useState();
const listener = (e) => {
setBodyOffset(document.body.getBoundingClientRect());
setScrollY(-bodyOffset.top);
setScrollX(bodyOffset.left);
setScrollDirection(lastScrollTop > -bodyOffset.top ? 'down' : 'up');
setLastScrollTop(-bodyOffset.top);
};
useEffect(() => {
window.addEventListener('scroll', listener);
return () => {
window.removeEventListener('scroll', listener);
};
}, []);
return {
scrollY,
scrollX,
scrollDirection
};
}
@joshuacerbito
Copy link

Hi! I updated this gist since it had 2 issues on it.

  1. Is the typo error on line 12, where it should've been setScrollY
  2. In line 29, the dependency array should not be present for that effect.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment