Download v4/src/hooks/useScrollDirection.js from Devendra174/react-code-dataset: direct link, hf CLI and curl.
- Browser
- Download file 1.3 kB
-
https://huggingface.co/datasets/Devendra174/react-code-dataset/resolve/1e92f2d0b9e054abc23a53595fd89ad3e2b4a34e/v4/src/hooks/useScrollDirection.js
- Command line
-
hf download hf://datasets/Devendra174/react-code-dataset@1e92f2d0b9e054abc23a53595fd89ad3e2b4a34e/v4/src/hooks/useScrollDirection.js
-
curl -L -o useScrollDirection.js https://huggingface.co/datasets/Devendra174/react-code-dataset/resolve/1e92f2d0b9e054abc23a53595fd89ad3e2b4a34e/v4/src/hooks/useScrollDirection.js
1.3 kB
| const SCROLL_UP = 'up'; | |
| const SCROLL_DOWN = 'down'; | |
| import { useState, useEffect } from 'react'; | |
| const useScrollDirection = ({ initialDirection, thresholdPixels, off } = {}) => { | |
| 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; | |
| } | |
| }; | |
| /** | |
| * Bind the scroll handler if `off` is set to false. | |
| * If `off` is set to true reset the scroll direction. | |
| */ | |
| !off ? window.addEventListener('scroll', onScroll) : setScrollDir(initialDirection); | |
| return () => window.removeEventListener('scroll', onScroll); | |
| }, [initialDirection, thresholdPixels, off]); | |
| return scrollDir; | |
| }; | |
| export default useScrollDirection; | |