Part V β The Craft Β· Lesson 10.7
Infinite Scroll
In one lineA sentinel element triggers the next page, and virtualization stops the DOM from growing forever.
Where you've seen itA social feed that scrolls beautifully for two minutes and then starts stuttering on every frame.
Diagram
How it works
- Use
IntersectionObserveron a sentinel with arootMarginso the next page starts before the user hits the bottom. - Guard against double-firing β the observer can trigger repeatedly while a request is in flight.
- Paginate by cursor, not offset (10.11) β new items arriving at the top will shift offsets and duplicate rows.
- Virtualize past a few hundred items with
react-windowor TanStack Virtual; without it, DOM size is the bottleneck. - Preserve scroll position on back-navigation by caching the loaded pages and the offset (6.9).
useEffect(() => {
const io = new IntersectionObserver(([entry]) => {
if (entry.isIntersecting && !loading && hasMore) loadNext();
}, { rootMargin: '400px' });
io.observe(sentinelRef.current);
return () => io.disconnect();
}, [loading, hasMore]);Trade-offs
| Infinite scroll | Pagination |
|---|---|
| Effortless browsing, mobile-friendly | Deep-linkable, position obvious |
| Footer unreachable | Footer reachable |
| Harder to return to an item | "Page 4" is a real address |
| Needs virtualization to stay fast | DOM stays small naturally |
Accessibility (8.3): announce loaded batches via a polite live region, never move focus on load, and provide a "Load more" button as a keyboard-operable alternative β a keyboard user cannot trigger a scroll sentinel easily.
Interview angle
"Build an infinite feed. What breaks first?"
- The DOM: without virtualization, memory and scroll performance degrade after a few hundred items.
- Offsets: with items being inserted at the top, offset pagination duplicates and skips β use cursors.
- Then the details that get skipped: the double-fire guard, the end state, scroll restoration, and a keyboard-accessible load-more.
Recap
IntersectionObserveron a sentinel withrootMargin, guarded against double-firing.- Virtualize once lists get long β that's the actual scaling limit.
- Cursor pagination, scroll restoration, and a keyboard alternative are what separate a demo from a feature.