Skip to content

Instantly share code, notes, and snippets.

@rw3iss
Created November 24, 2021 02:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rw3iss/71e7a03fc4374e670ef0c96024f10bd3 to your computer and use it in GitHub Desktop.
Save rw3iss/71e7a03fc4374e670ef0c96024f10bd3 to your computer and use it in GitHub Desktop.
useScrollDirection.js
import { useEffect, useRef, useState } from 'react';
export function useScrollDirection(element = window) {
const prevScrollY = useRef(0)
const [goingUp, setGoingUp] = useState(false);
const handleScroll = () => {
const currentScrollY = element.scrollTop;
if (prevScrollY.current < currentScrollY && goingUp) {
setGoingUp(false);
}
if (prevScrollY.current > currentScrollY && !goingUp) {
setGoingUp(true);
}
prevScrollY.current = currentScrollY;
};
useEffect(() => {
element.addEventListener("scroll", handleScroll);
return () => element.removeEventListener("scroll", handleScroll);
}, [goingUp]);
return goingUp ? 'up' : 'down';
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment