Vue Query 08 ⚡ Infinite Queries & Scrolling — Implementing cursor/offset pagination with useInfiniteQuery, initialPageParam, and maxPages
Infinite scrolling is a staple of modern web applications, from social media feeds to product catalogs. It provides a seamless discovery experience by appending new data as the user reaches the bottom of the page, rather than forcing the user to navigate through numbered pages. However, implementing infinite scrolling from scratch is fraught with complexity: you must manage the state of multiple fetched pages, track the “next page” cursor, decide when to trigger the fetch (e.g., intersection observers), and ensure the cache is invalidated correctly when data changes.
Vue Query simplifies this paradigm with the useInfiniteQuery hook. This hook abstracts the complexity of managing a list of pages, handling the storage and concatenation of results automatically. It provides primitives to determine if there is more data, fetch the next set of results, and handle the “end of the list” state, all while maintaining the benefits of Vue Query’s caching and background revalidation.
This chapter covers the full implementation of infinite queries, focusing on the configuration required for cursor-based pagination. We will walk through the getNextPageParam logic, the use of initialPageParam for proper hydration, and the configuration of maxPages to manage memory usage. By the end of this guide, you will be able to build a robust infinite scroll system that is both performant and resilient.
Key point: useInfiniteQuery transforms independent page requests into a single, unified list of data, managing the fetching, storage, and cursor orchestration automatically so you only need to focus on the UI and the fetch logic.
Why exists
The State Management Burden. Manually merging page 1, page 2, and page 3 into a single array is tedious. If you delete an item on page 2, you have to find that index in the global list and perform a splice. useInfiniteQuery manages this concatenation for you, treating the pages as a structured list while keeping the underlying API logic decoupled.
The Cursor/Offset Complexity. Different APIs use different pagination styles: some use page numbers (offset), while others use cursor tokens (ID of the last item). Managing these two distinct strategies across a large application requires a standardized interface. Vue Query provides a consistent API that abstracts these differences away.
The “Load More” Synchronization. Triggering a fetch when the user reaches the bottom of the page involves event listeners, throttle/debounce logic, and state checks. While Vue Query doesn’t handle the DOM detection, it provides the clean fetchNextPage and hasNextPage primitives that integrate perfectly with intersection observers.
The Memory & Cache Management. If a user scrolls through 50 pages of content, your application’s memory usage grows. If you aren’t careful, keeping all that in the cache can lead to performance degradation. maxPages and cache configuration allow you to prune old pages while keeping the current view intact.
The Hydration/SSR Challenge. SSR and infinite lists are difficult because the server needs to render the initial page, and the client needs to seamlessly “take over” the scrolling functionality. Vue Query’s infrastructure provides a clear path for serializing and hydrating infinite state so the user doesn’t see a jump or duplicate data loading.
a. The Infinite Query Lifecycle
useInfiniteQuery is structurally similar to useQuery, but with key differences in its configuration. You must provide a getNextPageParam function, which receives the last page of data and the list of all pages, and returns the information required to fetch the next page (the “cursor” or “page number”).
const { data, fetchNextPage, hasNextPage, isFetchingNextPage } = useInfiniteQuery({
queryKey: ['projects'],
queryFn: ({ pageParam }) => fetchProjects(pageParam),
initialPageParam: 1, // Start at page 1
getNextPageParam: (lastPage, allPages) => {
// If the last page has no items, return undefined to stop fetching
return lastPage.nextCursor ?? undefined;
},
});
The pageParam property in queryFn is automatically provided by Vue Query. On the first load, it is set to initialPageParam. Every subsequent call to fetchNextPage uses the return value from getNextPageParam as the pageParam. This creates a clean, circular dependency where the API response informs the next request.
The data object returned is not a single value, but an object containing two arrays: pages (the raw API responses for each page) and pageParams (the cursor/offset used to fetch each page). You typically flatten these in a computed property to render your list.
const flatItems = computed(() =>
data.value?.pages.flatMap(page => page.items) ?? []
);
b. Managing Cursor/Offset Strategies
The beauty of getNextPageParam is that it supports any pagination strategy. For Offset Pagination, you simply return the next integer. For Cursor Pagination, you return the ID or token of the last item in the list.
// Offset Pagination
getNextPageParam: (lastPage, allPages) => {
return lastPage.nextPage < lastPage.totalPages ? lastPage.nextPage : undefined;
},
// Cursor Pagination
getNextPageParam: (lastPage) => {
return lastPage.items.length > 0 ? lastPage.items[lastPage.items.length - 1].id : undefined;
}
If your API does not return a “next” indicator, you can return undefined to tell Vue Query there is no more data. Setting hasNextPage to false is the standard way to hide your “Load More” button or disable your intersection observer. Always return undefined explicitly when the list is exhausted; null or 0 might trigger a false positive where the fetcher tries to load the “0th” page.
c. Optimizations: maxPages and Caching
As users scroll indefinitely, the number of cached pages grows. maxPages allows you to limit the number of pages retained in the cache. Once the limit is exceeded, Vue Query automatically removes the oldest pages from the cache, keeping memory usage constant even if the user scrolls for hours.
useInfiniteQuery({
queryKey: ['projects'],
queryFn: ({ pageParam }) => fetchProjects(pageParam),
initialPageParam: 1,
getNextPageParam: ...,
maxPages: 5, // Keep only the last 5 pages in cache
});
If you need to refresh an infinite list (e.g., a “Pull to Refresh” or “Sort” change), refetch() will reload the entire list from page 1. This is usually the desired behavior for a sort change, but for simple refreshes, you might want to consider invalidateQueries with an exact match to force the cache to clear and re-start the process from initialPageParam.
Complete Example Session
// ============================================
// PART 1: THE INFINITE QUERY SETUP
// ============================================
import { useInfiniteQuery } from '@tanstack/vue-query';
import { computed } from 'vue';
const {
data,
fetchNextPage,
hasNextPage,
isFetchingNextPage,
status,
} = useInfiniteQuery({
queryKey: ['infinite-list'],
queryFn: ({ pageParam }) => fetchList(pageParam),
initialPageParam: 0,
getNextPageParam: (lastPage) => lastPage.nextCursor || undefined,
maxPages: 3, // Memory optimization
});
// ============================================
// PART 2: FLATTENING DATA FOR THE UI
// ============================================
const items = computed(() =>
data.value?.pages.flatMap((page) => page.items) ?? []
);
// ============================================
// PART 3: THE "LOAD MORE" TRIGGER
// ============================================
// Usage in template:
// <button @click="fetchNextPage" :disabled="!hasNextPage || isFetchingNextPage">
// {{ isFetchingNextPage ? 'Loading...' : 'Load More' }}
// </button>
// ============================================
// PART 4: PAGINATION WITH TOTAL PAGES (OFFSET)
// ============================================
const { ... } = useInfiniteQuery({
queryKey: ['projects'],
queryFn: ({ pageParam }) => fetchProjects({ page: pageParam }),
initialPageParam: 1,
getNextPageParam: (lastPage, allPages) => {
return lastPage.page < lastPage.total ? lastPage.page + 1 : undefined;
}
});
// ============================================
// PART 5: ERROR HANDLING
// ============================================
// if (status.value === 'error') // Show error UI
// ============================================
// PART 6: PREFETCHING NEXT PAGE (USER OPT-IN)
// ============================================
// Simply call fetchNextPage()
// ============================================
// PART 7: RE-FETCHING FROM START
// ============================================
// const { refetch } = ...
// refetch(); // Resets the list to page 1
// ============================================
// PART 8: INITIAL PAGE PARAM (SSR/Hydration)
// ============================================
// Essential for hydrating server-side lists correctly
// ============================================
// PART 9: DETECTING END OF LIST
// ============================================
// if (hasNextPage.value === false) // Hide load more
// ============================================
// PART 10: CUSTOMIZING PAGE PARAM SERIALIZATION
// ============================================
// (If API uses complex objects as cursors)
The example above captures the essential boilerplate for infinite scrolling, flattening the data for rendering, and configuring the cursor/offset logic.
Quick Reference
Hooks & Primitives
| Primitive | Usage |
|---|---|
fetchNextPage | Triggers the next fetch using the next cursor |
hasNextPage | Boolean: is there more data to load? |
isFetchingNextPage | Boolean: is a background load in progress? |
data.pages | Array of response objects |
data.pageParams | Array of cursors/page numbers used |
Configuration Options
| Option | Required | Purpose |
|---|---|---|
queryKey | Yes | Unique identifier for cache |
queryFn | Yes | The actual API call function |
initialPageParam | Yes | The cursor for the first page load |
getNextPageParam | Yes | Logic to extract next cursor from current page |
maxPages | No | Limit cache size (prevents RAM bloat) |
Best Practices
✅ Do This:
// Flatten pages into a single computed array for the UI
const items = computed(() => data.value?.pages.flatMap(p => p.items)); // ✅
// Use undefined to signal "no more pages"
return lastPage.next ? lastPage.next : undefined; // ✅
// Always check hasNextPage before calling fetchNextPage
if (hasNextPage.value) fetchNextPage(); // ✅
// Set maxPages for long-running sessions
maxPages: 5 // ✅
❌ Don’t Do This:
// Manually concatenate arrays in the fetcher
// (Let useInfiniteQuery handle the structure) // ❌
// Use 0 or null to signal end of list
// (Vue Query interprets these as valid page params) // ❌
// Forget to handle the loading state during fetchNextPage
// (Users might spam the load button) // ❌
Common Pitfalls
| Pitfall | Why It Happens | Fix |
|---|---|---|
| Infinite Loop | getNextPageParam always returns a value | Return undefined when done |
| Page Jump | initialPageParam mismatch | Ensure initialPageParam matches API default |
| Duplicate Fetches | Intersection observer triggers while fetching | Check isFetchingNextPage before trigger |
| Lost State | Using refetch when only fetchNextPage is needed | refetch resets to page 1, which isn’t always desired |
| Memory Bloat | Large lists never pruned | Set maxPages to keep memory consumption stable |
Real-World Examples
1. Cursor Pagination
getNextPageParam: (last) => last.cursor ?? undefined
2. Integer Offset Pagination
getNextPageParam: (last, all) => all.length < last.total ? all.length + 1 : undefined
3. Handling API “Empty” states
return last.items.length === 0 ? undefined : last.next
4. Intersection Observer Trigger
onIntersection: () => { if (hasNextPage.value) fetchNextPage() }
5. Resetting List
const reset = () => refetch() // Resets to initialPageParam
6. Disabling “Load More”
<button :disabled="!hasNextPage || isFetchingNextPage">...</button>
7. Tracking Page Params
const lastPageParam = computed(() => data.value?.pageParams.at(-1))
8. Hydration with SSR
// Ensure initialPageParam matches the server-rendered page 1
9. Complex Cursor Object
getNextPageParam: (last) => ({ ...last.meta, id: last.lastId })
10. Memory Capping
maxPages: 10 // Prune after 10 pages scroll
Visual
The Flattened Page Structure
┌──────────────────────────────────────────────────────────┐
│ API RESPONSES (Stored in 'pages') │
│ Page 1: [A, B] │
│ Page 2: [C, D] │
│ Page 3: [E, F] │
│ │
│ FLATTENED FOR UI (Computed) │
│ [A, B, C, D, E, F] │
└──────────────────────────────────────────────────────────┘
Infinite Fetch Lifecycle
┌──────────────────────────────────────────────────────────┐
│ Trigger fetchNextPage() │
│ │ │
│ ▼ │
│ Call queryFn({ pageParam: lastCursor }) │
│ │ │
│ ▼ │
│ Update cache -> pages.push(newItems) │
│ │ │
│ ▼ │
│ Re-compute flat list -> UI Update │
└──────────────────────────────────────────────────────────┘
Cache Pruning (maxPages)
┌──────────────────────────────────────────────────────────┐
│ maxPages: 2 │
│ │
│ 1. Fetch Page 1: [Page 1] (Cache) │
│ 2. Fetch Page 2: [Page 1, Page 2] (Cache) │
│ 3. Fetch Page 3: [Page 2, Page 3] (Page 1 Evicted) │
└──────────────────────────────────────────────────────────┘
Summary
| Item | Value |
|---|---|
| Hook | useInfiniteQuery |
| Flattening | .flatMap(page => page.items) |
| Cursor Logic | getNextPageParam |
| Stop Trigger | return undefined |
| UX Control | isFetchingNextPage, hasNextPage |
| Memory Control | maxPages |
| Reset | refetch() |
Key takeaways:
- Use
useInfiniteQueryfor lists. It is designed exactly for scenarios where data grows dynamically, abstracting away the merging and state management of paginated pages . - Always flatten your pages. The raw data returned by
useInfiniteQueryis nested (pages/pageParams). Use acomputedproperty with.flatMap()to create a clean, single array for your rendering loop . - Explicitly stop fetching. The
getNextPageParamfunction is the gatekeeper. Returningundefinedis the standard signal to Vue Query that no further data exists . - Handle the “Load More” UI state. Always use
hasNextPageto show/hide triggers andisFetchingNextPageto prevent redundant network requests . - Manage memory with
maxPages. If you have an infinite-scrolling feed, you can easily exhaust memory. Use themaxPagesoption to prune the cache effectively . - Cursor or Offset? Both work. The power of
getNextPageParamis its flexibility; it can handle simple page increments as easily as complex cursor tokens .
Remember: Infinite loading is just a sequence of page fetches tied together. By leveraging Vue Query’s built-in state management for lists, you can build seamless, memory-efficient scrolling experiences without writing custom merge logic.
Stop using slow, ad-bloated tool sites! 🤮
🔎 Search “KandZ Tools” on Google to use many professional utilities for free.
KandZ.me is the ultimate minimalist hub for:
✅ Finance (Mortgage, Interest, Inflation)
✅ Tech (Base64, JSON, Dev Suite, IP)
✅ Health (BMI, BMR, TDEE)
✅ Productivity (Timer, Workspace, QR)
⚡️ Fast & Private
🔒 No data leaves your device
💎 100% Free
🔗 Use it now: https://tools.kandz.me
🔖 Bookmark it—you’ll need it later!