Created
July 2, 2020 04:37
-
-
Save zoubingwu/7441839c7c43ce6b2b1688532dfb0a25 to your computer and use it in GitHub Desktop.
infinite scroller hook
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 { 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