Created
November 13, 2025 22:15
-
-
Save remarkablemark/c618b41c6b17ad8d55ccb2b39b5ee714 to your computer and use it in GitHub Desktop.
React hook useScrollDirection
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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