Skip to content

Instantly share code, notes, and snippets.

@MartinPavlik
Last active November 8, 2020 01:06
Show Gist options
  • Save MartinPavlik/22db8d715cfd28714ffaed9f59433bfb to your computer and use it in GitHub Desktop.
Save MartinPavlik/22db8d715cfd28714ffaed9f59433bfb to your computer and use it in GitHub Desktop.
React useScrollDirection hook
import { useEffect, useState } from 'react';
export const SCROLL_UP = 'up';
export const SCROLL_DOWN = 'down';
export const useScrollDirection = (initialDirection = SCROLL_DOWN, thresholdPixels = 64) => {
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;
}
};
window.addEventListener('scroll', onScroll);
return () => window.removeEventListener('scroll', onScroll);
},
[initialDirection, thresholdPixels],
);
return scrollDir;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment