Skip to content

Instantly share code, notes, and snippets.

@zoubingwu
Created July 2, 2020 04:37
Show Gist options
  • Save zoubingwu/7441839c7c43ce6b2b1688532dfb0a25 to your computer and use it in GitHub Desktop.
Save zoubingwu/7441839c7c43ce6b2b1688532dfb0a25 to your computer and use it in GitHub Desktop.
infinite scroller hook
import { useRef, useCallback } from "react";
function useInfiniteScroll(doSomething) {
const ticking = useRef(false);
const enteredRedZone = useRef(false);
return useCallback(
event => {
if (!ticking.current) {
event.persist();
window.requestAnimationFrame(() => {
const scrollableRange =
event.target.scrollHeight - event.target.clientHeight;
if (event.target.scrollTop / scrollableRange >= 0.95) {
if (!enteredRedZone.current) {
doSomething();
}
enteredRedZone.current = true;
} else {
enteredRedZone.current = false;
}
ticking.current = false;
});
ticking.current = true;
}
},
[doSomething]
);
}
// const onScroll = useInfiniteScroll(() => console.log("do something"));
// return <div onScroll={onScroll}></div>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment