Last active
June 4, 2019 07:31
-
-
Save NklsJ/9cab0809bc7d0e0dc423b1e64a815b55 to your computer and use it in GitHub Desktop.
Simple react hook for getting window Y scroll position
This file contains 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 {useState, useEffect} from 'react' | |
const useScrollPosition = () => { | |
const [scrollPosition, setScrollPosition] = useState(-1) | |
useEffect(() => { | |
const handleScroll = () => setScrollPosition(window.scrollY) | |
window.addEventListener('scroll', handleScroll) | |
/** | |
* Initialize with correct scroll position once. | |
* | |
* If user refreshes page when he/she has scrolled down the page already the scroll position | |
* needs to be preserved. | |
*/ | |
if (scrollPosition < 0) | |
handleScroll() | |
return () => window.removeEventListener('scroll', handleScroll) | |
}) | |
return scrollPosition | |
} | |
export default useScrollPosition |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment