Data Fetching & APIs
React Pagination and Infinite Scroll
Pagination requests one page at a time and replaces the list; infinite scroll appends the next page as the user reaches the bottom, usually detected with an IntersectionObserver.
What is Pagination and Infinite Scroll in React?
Pagination requests one page at a time and replaces the list; infinite scroll appends the next page as the user reaches the bottom, usually detected with an IntersectionObserver.
Pagination and Infinite Scroll example
const sentinelRef = useRef(null);
useEffect(() => {
const observer = new IntersectionObserver(entries => {
if (entries[0].isIntersecting && hasMore && !loading) {
setPage(p => p + 1);
}
}, { rootMargin: '200px' });
const el = sentinelRef.current;
if (el) observer.observe(el);
return () => observer.disconnect();
}, [hasMore, loading]);
<div ref={sentinelRef} />How this works
The observer fires when the empty sentinel div scrolls near the viewport. rootMargin loads the next page slightly before the user actually reaches the bottom, so the wait is invisible.
Key points to remember
- Guard on loading, or a fast scroll fires several page requests at once.
- Disconnect the observer in the cleanup.
- Prefer numbered pagination for content that must be crawlable and linkable.
- Offer a "Load more" button as a fallback — infinite scroll is hard to use with a keyboard.
Common mistakes with Pagination and Infinite Scroll
- Infinite scroll on a page with a footer, which becomes unreachable.
- Appending duplicates because the same page number was requested twice.
React Pagination and Infinite Scroll— Interview Questions & FAQs
Is infinite scroll bad for SEO?+
It can be, because content behind scroll events may never be crawled and individual pages have no URL. Pair it with real paginated URLs, or use numbered pagination for content you want indexed.
