Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
import { useEffect, useState } from 'react';
// this func do not cover all the cases
function debounce(func, wait = 100) {
let timeout;
return function(...args) {
clearTimeout(timeout);
timeout = setTimeout(() => {
func.apply(this, args);
}, wait);
};
}
const padding = 500; // gap from bottom
const useInfiniteScroll = cb => {
const [isFetching, setIsFetching] = useState(false);
const [stopScroll, setStopScroll] = useState(false);
const handleScroll = debounce(function handleScroll(e) {
if (
window.innerHeight + window.pageYOffset >=
document.body.offsetHeight - padding
) {
stopScroll
? window.removeEventListener('scroll', handleScroll)
: setIsFetching(true);
}
});
useEffect(() => {
window.addEventListener('scroll', handleScroll);
return () => window.removeEventListener('scroll', handleScroll);
}, []);
useEffect(() => {
if (!isFetching) return;
if (stopScroll) {
setIsFetching(false);
return;
}
cb();
}, [isFetching, stopScroll]);
return [isFetching, setIsFetching, param => setStopScroll(param)];
};
export default useInfiniteScroll;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment