Skip to content
Tutorials Center
My learning

Topics

Lesson 23 of 38 ยท Pagination and Infinite Queries

Infinite Scroll Patterns

Build infinite scrolling with useInfiniteQuery: an IntersectionObserver sentinel, bidirectional lists with fetchPreviousPage, maxPages, and search-driven feeds.

A Load more button is explicit and accessible. Infinite scrolling feels smoother because new items arrive as the user nears the end. The query side is the same useInfiniteQuery you already know; the new part is detecting the end of the list and calling fetchNextPage for the user.

This lesson builds that with the browser's IntersectionObserver, then covers the harder variants: scrolling up for older messages, limiting memory with maxPages, resetting when a search term changes, and the guard rails that prevent request storms.

The sentinel pattern

Put an empty element (the sentinel) after the last item. Observe it with IntersectionObserver. When it enters the viewport, call fetchNextPage(). No scroll event handlers and no pixel math.

JSX
function useSentinel(onVisible, enabled) {
  const ref = React.useRef(null);
  React.useEffect(() => {
    if (!enabled || !ref.current) return;
    const observer = new IntersectionObserver(([entry]) => {
      if (entry.isIntersecting) onVisible();
    }, { rootMargin: "120px" });
    observer.observe(ref.current);
    return () => observer.disconnect();
  }, [onVisible, enabled]);
  return ref;
}

rootMargin: "120px" fires slightly before the sentinel is on screen so the next page is usually ready by the time the user arrives. The enabled flag is the guard rail: pass hasNextPage && !isFetchingNextPage, so a second request never starts while one is running and the observer is removed at the end of the list.

Infinite scroll with a sentinel

Scroll inside the box. Pages arrive before you hit the bottom, and the counter stops at 4. Note root: document.getElementById("box"): when the scrolling happens inside an element rather than the window, that element must be the observer's root.

If the first page is shorter than the container, the sentinel is already visible and never "enters", so nothing triggers. Keep the observer effect depending on canLoad (as above): after each page loads, the effect re-runs, observes again, and the callback fires immediately if the sentinel is still on screen.

Scrolling up: fetchPreviousPage

Chat apps open at the newest message and load older ones when you scroll to the top. useInfiniteQuery supports both directions through getPreviousPageParam, fetchPreviousPage, hasPreviousPage and isFetchingPreviousPage:

JavaScript
useInfiniteQuery({
  queryKey: ["chat"],
  queryFn: ({ pageParam }) => fetchMessages(pageParam),
  initialPageParam: 100,                       // start near the newest message
  getPreviousPageParam: (firstPage) => firstPage.olderCursor,
  getNextPageParam: (lastPage) => lastPage.newerCursor,
})

New pages from fetchPreviousPage are prepended to data.pages. Your render code does not change, but the scroll position does: adding content above the viewport pushes everything down. Store scrollHeight before the fetch and add the difference to scrollTop afterwards (in a layout effect) to keep the user where they were.

Limiting memory with maxPages

A feed that runs for an hour can accumulate thousands of rows, and a refetch would reload every page. maxPages caps the number of pages kept. When it is exceeded, the page on the opposite end of the scroll direction is dropped:

JavaScript
useInfiniteQuery({ /* ... */ maxPages: 3 })

This only works well if you also define getPreviousPageParam, because dropped pages must be re-loadable when the user scrolls back. Pair it with virtualized rendering for lists of thousands of rows.

A search-driven feed

Put the search term in the key, exactly as you did for paged lists:

JavaScript
useInfiniteQuery({
  queryKey: ["feed", { search }],
  queryFn: ({ pageParam }) => fetchFeed({ search, cursor: pageParam }),
  initialPageParam: 0,
  getNextPageParam: (last) => last.next,
})

Changing search selects a new cache entry that starts at the first page, and the old results remain cached for when the user goes back. Combine it with a debounced input so you do not fire a query for every keystroke.

Search resets the feed

Switch between the terms and watch the request counter: going back to a term you already searched shows cached results immediately.

Accessibility and fallbacks

Infinite scroll can trap keyboard users: the footer becomes unreachable because the list keeps growing. Offer a visible "Load more" button as a fallback, keep a stable aria-live status ("20 results loaded"), and do not place important links below the list. For SEO pages that must be crawlable, provide real paginated URLs and use infinite scroll only as an enhancement.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What should trigger fetchNextPage in the sentinel pattern?

    The sentinel element plus IntersectionObserver is declarative and avoids pixel math and scroll handlers.
  2. 2. Why pass hasNextPage && !isFetchingNextPage as the guard?

    Without the guard the observer can call fetchNextPage repeatedly while one is in flight, or after the list has ended.
  3. 3. Where do pages loaded by fetchPreviousPage go?

    Previous pages are prepended, which is why you must adjust the scroll position to avoid a visual jump.
  4. 4. How should a search term affect an infinite query?

    A different key means a separate cache entry that starts from the first page, and old results stay cached.

Summary

  • Observe a sentinel with IntersectionObserver and call fetchNextPage when it appears.
  • Guard with hasNextPage && !isFetchingNextPage to avoid duplicate requests.
  • Use getPreviousPageParam and fetchPreviousPage for lists that grow upward; correct the scroll position.
  • maxPages limits memory and refetch cost; it needs both directions defined.
  • Keep searches and filters in the key, and offer a Load more fallback for accessibility.

Next: Optimistic UI with Variables