-
-
Save pocojang/5c98d0c9dcb8c7e8f7452e744bbd95b8 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
import { useEffect } from "react";
const useShortcut = ({ shortcut, onKeyDown }) => {
useEffect(() => {
const keyHandler = function(event) {
if (
shortcut &&
event.key === shortcut &&
event.target.tagName !== "INPUT"
) {
onKeyDown();
}
};
document.addEventListener("keydown", keyHandler);
return () => {
document.removeEventListener("keydown", keyHandler);
};
}, [onKeyDown, shortcut]);
};
export default useShortcut;