I see questions aplenty about useEffect and debounce but this use case is a little different. I was having some trouble with fetchBookList not having access to state variables in the same component and it turns out on mount that function only has access to "stale" state, hence this:
useEffect(() => {
const handleScroll = () => {
if (Math.ceil(window.innerHeight + window.scrollY) >= document.documentElement.scrollHeight) {
fetchBookList();
}
}
window.addEventListener('scroll', handleScroll, {
passive: true
});
return () => {
window.addEventListener('scroll', handleScroll);
}
}, [bookList, bookType])
Re-creating the handleScroll is not the optimal solution but it does work. The problem is, with this code when the user hits the bottom of the screen there's no throttling in place so instead of fetching just once, multiple calls go out as in an instant the viewport may or may not be at the very bottom of the screen.
In this particular case, how does one go about debouncing the fetchBookList call so it only fires once every second or so max?