Skip to content

Instantly share code, notes, and snippets.

@pocojang
Forked from almond-bongbong/useDetectScrollEnd.js
Created June 28, 2019 01:54
Show Gist options
  • Save pocojang/5c98d0c9dcb8c7e8f7452e744bbd95b8 to your computer and use it in GitHub Desktop.
Save pocojang/5c98d0c9dcb8c7e8f7452e744bbd95b8 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;
@pocojang
Copy link
Author

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;

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment