Skip to content

Instantly share code, notes, and snippets.

@apsolut
Forked from reecelucas/useScrollDirection.js
Created May 21, 2020 13:11
Show Gist options
  • Save apsolut/29cfa340cd87edc06f2b23dafed74e36 to your computer and use it in GitHub Desktop.
Save apsolut/29cfa340cd87edc06f2b23dafed74e36 to your computer and use it in GitHub Desktop.
React hook to detect scroll direction, based on the API of https://github.com/dollarshaveclub/scrolldir
const SCROLL_UP = "up";
const SCROLL_DOWN = "down";
const useScrollDirection = ({
initialDirection,
thresholdPixels,
off
} = {}) => {
const [scrollDir, setScrollDir] = useState(initialDirection);
useEffect(() => {
const threshold = thresholdPixels || 0;
let lastScrollY = window.pageYOffset;
let ticking = false;
const updateScrollDir = () => {
const scrollY = window.pageYOffset;
if (Math.abs(scrollY - lastScrollY) < threshold) {
// We haven't exceeded the threshold
ticking = false;
return;
}
setScrollDir(scrollY > lastScrollY ? SCROLL_DOWN : SCROLL_UP);
lastScrollY = scrollY > 0 ? scrollY : 0;
ticking = false;
};
const onScroll = () => {
if (!ticking) {
window.requestAnimationFrame(updateScrollDir);
ticking = true;
}
};
/**
* Bind the scroll handler if `off` is set to false.
* If `off` is set to true reset the scroll direction.
*/
!off
? window.addEventListener("scroll", onScroll)
: setScrollDir(initialDirection);
return () => window.removeEventListener("scroll", onScroll);
}, [initialDirection, thresholdPixels, off]);
return scrollDir;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment