Skip to content

Instantly share code, notes, and snippets.

@remarkablemark
Created November 13, 2025 22:15
Show Gist options
  • Select an option

  • Save remarkablemark/c618b41c6b17ad8d55ccb2b39b5ee714 to your computer and use it in GitHub Desktop.

Select an option

Save remarkablemark/c618b41c6b17ad8d55ccb2b39b5ee714 to your computer and use it in GitHub Desktop.
React hook useScrollDirection
import { useCallback, useEffect, useRef, useState } from "react";
export enum ScrollDirection {
"up" = "up",
"down" = "down",
}
export function useScrollDirection() {
const scrollYRef = useRef(0);
const [direction, setDirection] = useState(ScrollDirection.up);
const scrollDirection = useCallback(() => {
setDirection(
window.scrollY > scrollYRef.current
? ScrollDirection.down
: ScrollDirection.up,
);
scrollYRef.current = window.scrollY;
}, []);
useEffect(() => {
window.addEventListener("scroll", scrollDirection);
return () => {
window.removeEventListener("scroll", scrollDirection);
};
}, [scrollDirection]);
return direction;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment