Created
June 26, 2019 01:51
-
-
Save almond-bongbong/8ee2e1c7a6073ab3d5998ca5bc89112b to your computer and use it in GitHub Desktop.
custom hook for detecting scroll end
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, useRef, useEffect, useCallback } from 'react'; | |
import throttle from 'lodash/throttle'; | |
const useDetectScrollEnd = (endPercent = 0.9) => { | |
const scrollEnded = useRef(false); | |
const [isScrollEnd, setIsScrollEnd] = useState(false); | |
const handleScroll = useCallback(throttle(() => { | |
const { scrollY, innerHeight } = window; | |
const scrollPercent = (scrollY + innerHeight) / document.body.scrollHeight; | |
if (scrollPercent >= endPercent && !scrollEnded.current) { | |
scrollEnded.current = true; | |
setIsScrollEnd(true); | |
} | |
if (scrollPercent < endPercent && scrollEnded.current) { | |
scrollEnded.current = false; | |
setIsScrollEnd(false); | |
} | |
}, 500), [endPercent]); | |
useEffect(() => { | |
window.addEventListener('scroll', handleScroll); | |
return () => { | |
window.removeEventListener('scroll', handleScroll); | |
}; | |
}, [handleScroll]); | |
return isScrollEnd; | |
}; | |
export default useDetectScrollEnd; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment