Full answer
A scroll event handler fires continuously and needs layout measurements. IntersectionObserver tells you asynchronously when an element enters the viewport and is the standard tool.
Design: the list shows items loaded so far. After the last item, an empty sentinel element sits in the DOM. An observer watches it. When it becomes visible, the component loads the next page and appends the items. Appending pushes the sentinel out of view, and the cycle repeats as the user scrolls.
State: items, page (or a cursor), loading and hasMore. The effect that creates the observer depends on the load function and the state it needs. Create the observer in the effect, observe the sentinel stored in a ref, and return observer.disconnect() as cleanup.
Correctness details. Guard re-entry: do nothing if loading is true or hasMore is false, so quick visibility changes cannot load the same page twice. Use functional updates when appending to avoid losing items. When the last page arrives, set hasMore to false and stop rendering the sentinel. Handle errors with a retry button so the user is not stuck. If the first page does not fill the screen, the sentinel is still visible and the observer fires again, so the screen fills without more code.
Extras: rootMargin: '200px' starts loading before the sentinel is visible, virtualization keeps the DOM small for thousands of rows, and cursor-based pagination is safer than page numbers when data changes. In a library-based app, TanStack Query's useInfiniteQuery manages pages, and the sentinel only calls fetchNextPage.
The example loads pages from a fake API of 25 items.
import { useCallback, useEffect, useRef, useState } from 'react';
const TOTAL = 25;
const PAGE_SIZE = 10;
function fetchPage(page) {
return new Promise((resolve) =>
setTimeout(() => {
const start = page * PAGE_SIZE;
const end = Math.min(start + PAGE_SIZE, TOTAL);
resolve(Array.from({ length: end - start }, (_, i) => 'Lesson ' + (start + i + 1)));
}, 10)
);
}
export default function LessonList() {
const [items, setItems] = useState([]);
const [page, setPage] = useState(0);
const [loading, setLoading] = useState(false);
const [hasMore, setHasMore] = useState(true);
const sentinelRef = useRef(null);
const loadMore = useCallback(async () => {
if (loading || !hasMore) return;
setLoading(true);
const next = await fetchPage(page);
setItems((current) => [...current, ...next]);
setPage((p) => p + 1);
setHasMore((page + 1) * PAGE_SIZE < TOTAL);
setLoading(false);
}, [loading, hasMore, page]);
useEffect(() => {
const node = sentinelRef.current;
if (!node) return;
const observer = new IntersectionObserver(
(entries) => {
if (entries[0].isIntersecting) loadMore();
},
{ rootMargin: '200px' }
);
observer.observe(node);
return () => observer.disconnect();
}, [loadMore, hasMore]);
return (
<div>
<ul>
{items.map((item) => (
<li key={item}>{item}</li>
))}
</ul>
{hasMore && <div ref={sentinelRef} data-sentinel>{loading ? 'Loading...' : ''}</div>}
</div>
);
}The runner has no layout, so the check used a small IntersectionObserver stand-in and called its callback to simulate the sentinel becoming visible. Output of the run: first page: 0 items after sentinel visible 1: 10 items after sentinel visible 2: 20 items after a third time: 25 items sentinel still shown: false
Key points
- Observe a sentinel after the list with IntersectionObserver instead of scroll listeners.
- Create the observer in an effect and disconnect it in cleanup.
- Guard against loading while already loading and after the last page.
- Use rootMargin to prefetch and virtualization for very long lists.
- Use cursor pagination and useInfiniteQuery in production.
Common mistakes
- Using scroll events and reading layout values on every event.
- Not guarding against concurrent loads, so a page loads twice.
- Forgetting to disconnect the observer in cleanup.
- Keeping the sentinel after the last page, so the observer keeps firing.
- Rendering thousands of rows without virtualization.
Follow-ups
- How would you add error handling and a retry button?
- How would useInfiniteQuery change this code?
- How would you keep scroll position and performance with 10,000 items?
Tips
- Say why IntersectionObserver beats scroll handlers.
- Show the guard against double loads. It is the bug interviewers look for.
- Mention virtualization for long lists.