<-Day 4: Infinite Scroll
Main Logic: Detecting Bottom of Page for Infinite Scroll
Solution 1: Javascript
const handleScroll = () => {
// Check if user has scrolled to bottom of page
if (window.scrollY + window.innerHeight >= document.body.scrollHeight
&& !loading && hasMore) {
setPage(prev => prev + 1);
}
};
Solution 2: Javascript
// IntersectionObserver(callback,{threshold})
useEffect(() => {
const observer = new IntersectionObserver(entries => {
const firstEntry = entries[0];
if (firstEntry.isIntersecting && !loading && hasMore)
{
setPage(prev => prev + 1);
}
},
{ threshold: 1.0 }
)
if(loaderRef.current){
observer.observe(loaderRef.current);
}
return ()=> observer.disconnect();
},[loading, hasMore]);
Key Components:
- window.scrollYCurrent scroll position from top
- window.innerHeightHeight of browser viewport
- document.body.scrollHeightTotal scrollable height
- loadingPrevents multiple simultaneous requests
- hasMoreIndicates if more content is available