Pagination and Infinite Scrolling Patterns
What you'll learn: How useInfiniteQuery from TanStack Query handles pagination without messy useEffect dependencies.
The Problem with Manual Pagination
In the last lesson, you saw TanStack Query handle simple data fetching. But what about loading pages of results — like scrolling through a social feed or clicking "Load More"?
With manual useEffect, you'd track a page number in state, add it to the dependency array, fight race conditions when the user clicks fast, and write cleanup logic. It gets messy quickly.
How useInfiniteQuery Works
TanStack Query's useInfiniteQuery hook manages pagination state for you. You just tell it:
- How to fetch a page (given a cursor or page number)
- How to extract the "next page" info from each response
It handles:
- Loading the first page on mount
- Storing all pages in order
- Providing a
fetchNextPage()function you call when the user scrolls or clicks - Tracking
hasNextPageandisFetchingNextPagestates automatically
The Mental Model
Think of useInfiniteQuery like a librarian who remembers which chapters you've read and automatically fetches the next one when you ask — without you managing a stack of bookmarks.
For cursor-based APIs (like "nextToken: abc123"), it extracts the cursor from each response.
For offset-based APIs (like page=1, page=2), it increments the page number for you.
No dependency arrays. No race conditions. No manual state management.
Why This Matters
Infinite scrolling is extremely common (Twitter, Instagram, product listings), but hard to implement cleanly with raw useEffect. useInfiniteQuery encapsulates the pattern so you focus on UI, not pagination logic.
Key Takeaway: useInfiniteQuery handles cursor or offset pagination automatically, eliminating complex useEffect dependency management and providing built-in states like hasNextPage and fetchNextPage().