Skip to content

Instantly share code, notes, and snippets.

@almond-bongbong
Created June 26, 2019 01:51
Show Gist options
  • Save almond-bongbong/8ee2e1c7a6073ab3d5998ca5bc89112b to your computer and use it in GitHub Desktop.
Save almond-bongbong/8ee2e1c7a6073ab3d5998ca5bc89112b to your computer and use it in GitHub Desktop.
custom hook for detecting scroll end
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