ReactHard
Infinite scroll logic
Infinite scroll loads the next page of data when the user nears the end of the list. The robust way is to place a sentinel element after the last item and watch it with IntersectionObserver (not scroll events), fetch the next page when it becomes visible, append results, and stop when there are no more pages. Guard against duplicate requests, handle errors with retry, and virtualize very long lists.
Steps
- State:
items,pageorcursor,hasMore,loading,error. - Render items plus a sentinel
<div>at the end. - Observe the sentinel with
IntersectionObserver(rootMargin: "200px"to prefetch before the bottom). - When it intersects and you are not already loading and
hasMore, fetch the next page. - Append items, update the cursor and
hasMorefrom the API response. - Disconnect the observer in cleanup.
Pitfalls to mention
- Duplicate fetches: the sentinel can fire several times; check a loading flag (a ref avoids stale closures).
- Cursor vs offset pagination: cursors avoid duplicates and gaps when data changes while scrolling.
- Race conditions: abort or ignore requests when filters change, and reset the list.
- Accessibility and UX: provide a "Load more" button fallback, keep focus stable, announce new items, and let users reach the footer.
- Performance: thousands of DOM nodes slow the page; virtualize (TanStack Virtual) and keep scroll restoration in mind.
Libraries
TanStack Query's useInfiniteQuery handles pages, fetchNextPage, hasNextPage and caching.
Code example
tsx
1import { useCallback, useEffect, useRef, useState } from "react";23type Post = { id: number; title: string };4type Page = { posts: Post[]; total: number; skip: number; limit: number };56export function InfiniteFeed() {7 const [posts, setPosts] = useState<Post[]>([]);8 const [hasMore, setHasMore] = useState(true);9 const [error, setError] = useState(false);10 const loadingRef = useRef(false);11 const sentinelRef = useRef<HTMLDivElement>(null);1213 const loadMore = useCallback(async () => {14 if (loadingRef.current || !hasMore) return; // prevent duplicate requests15 loadingRef.current = true;16 setError(false);17 try {18 const res = await fetch(`https://dummyjson.com/posts?limit=10&skip=${posts.length}&select=title`);19 const page: Page = await res.json();20 setPosts((prev) => [...prev, ...page.posts]);21 setHasMore(page.skip + page.limit < page.total);22 } catch {23 setError(true);24 } finally {25 loadingRef.current = false;26 }27 }, [posts.length, hasMore]);2829 useEffect(() => {30 const el = sentinelRef.current;31 if (!el) return;32 const io = new IntersectionObserver(([entry]) => entry.isIntersecting && loadMore(), { rootMargin: "200px" });33 io.observe(el);34 return () => io.disconnect();35 }, [loadMore]);3637 return (38 <div>39 <ul>{posts.map((p) => <li key={p.id} style={{ padding: 16 }}>{p.title}</li>)}</ul>40 {error && <button onClick={loadMore}>Retry</button>}41 {hasMore ? <div ref={sentinelRef} aria-hidden>Loading more…</div> : <p>You've reached the end.</p>}42 </div>43 );44}
Practice this question
Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the React set.