Last active
July 8, 2019 09:57
-
-
Save antoniocapelo/95dc3e25cd495191d78afac905d344d4 to your computer and use it in GitHub Desktop.
Custom React Hook for setting a passive scroll listener and get updated scrollY and scroll direction information
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
/** | |
* useScrollListener hook | |
* Usage: const { scrollY, scrollDirection } = useScrollListener(); | |
*/ | |
import { useState, useRef, useEffect } from 'react'; | |
export function useScroll() { | |
const [scrollY, setScrollY] = useState(0); | |
const [progress, setProgress] = useState(0); | |
const previousScrollY = useRef(); | |
const [scrollDirection, setScrollDirection] = useState("down"); | |
useEffect(() => { | |
previousScrollY.current = scrollY; | |
}); | |
useEffect(() => { | |
function listener() { | |
const scrollTop = | |
document.documentElement.scrollTop || document.body.scrollTop; | |
setScrollY(scrollTop); | |
setProgress( | |
scrollTop / (document.documentElement.offsetHeight - window.innerHeight) | |
); | |
const direction = previousScrollY.current < scrollTop ? "down" : "up"; | |
setScrollDirection(direction); | |
} | |
window.addEventListener("scroll", listener, { passive: true }); | |
return () => { | |
window.removeEventListener("scroll", listener, { passive: true }); | |
}; | |
}, []); | |
return { | |
scrollY, | |
progress, | |
scrollDirection | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment