Skip to content

Instantly share code, notes, and snippets.

@NklsJ
Last active June 4, 2019 07:31
Show Gist options
  • Save NklsJ/9cab0809bc7d0e0dc423b1e64a815b55 to your computer and use it in GitHub Desktop.
Save NklsJ/9cab0809bc7d0e0dc423b1e64a815b55 to your computer and use it in GitHub Desktop.
Simple react hook for getting window Y scroll position
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