Svelte Query 08 ⚡ Infinite Queries & Scrolling — Cursor and Offset Pagination with createInfiniteQuery
Modern web applications increasingly favor infinite scrolling interfaces over traditional page-numbered navigation. While simple pagination is straightforward, infinite scrolling introduces complex state challenges: you must track the sequence of loaded pages, append new data without discarding the old, and intelligently determine when to fetch the next set of items based on cursors or offset counters. Manually managing this “stitching” process is a primary source of bugs in data-heavy UIs.
Svelte Query solves this with the createInfiniteQuery hook. This primitive is designed specifically to handle the lifecycle of segmented data, providing automated state management for page accumulation and metadata tracking. By defining how to generate the “next” fetch request based on the data retrieved from the “current” request, you can build seamless experiences that scale as the user scrolls.
Key point: createInfiniteQuery automates the accumulation of paginated data by utilizing getNextPageParam to compute the next request’s cursor and stitching the resulting pages into a single reactive data.pages array, effectively offloading the entire pagination lifecycle to the framework.
Why exists
The data stitching problem. Appending arrays of new items to an existing set while ensuring that the UI remains reactive is complex. Without the framework, you are forced to manage manual array concatenations that often result in duplicate keys or lost state during re-fetches.
The cursor-tracking complexity. In cursor-based pagination, the “next” page is defined by the unique identifier of the last item in the current set. Managing this dependency—where Page N+1 requires the results of Page N—manually is prone to race conditions and synchronization errors.
The memory management challenge. As a user scrolls indefinitely, the document object model (DOM) and the application memory grow. Infinite query tools help manage the number of pages retained in the cache, ensuring the application doesn’t slow down after long sessions.
The prefetching requirement. For an infinite scroll to feel “instant,” the application must proactively fetch the next page before the user hits the bottom. createInfiniteQuery makes this predictive fetching declarative, moving logic out of UI components and into the query configuration.
The state synchronicity requirement. When a mutation occurs (like deleting an item), re-syncing an infinite scroll state is difficult because the data is spread across many pages. The framework’s ability to mutate the query cache directly makes this process reliable and consistent across the entire infinite stack.
a. The createInfiniteQuery primitive and initialPageParam
The createInfiniteQuery hook functions similarly to createQuery, but it manages an array of pages rather than a single result. The initialPageParam option is mandatory; it defines the value for the very first fetch (e.g., 0 for offsets or undefined for cursor-based initial requests).
const query = createInfiniteQuery({
queryKey: ['posts'],
queryFn: ({ pageParam }) => fetchPosts(pageParam),
initialPageParam: 1,
getNextPageParam: (lastPage) => lastPage.nextCursor
});
Every time you call fetchNextPage(), Svelte Query calls your queryFn again, passing the value returned by getNextPageParam as the pageParam. This encapsulates the entire pagination loop, allowing your components to simply trigger the next fetch without knowing the underlying offset or cursor logic.
b. Defining the infinite logic with getNextPageParam
The getNextPageParam function is the core of infinite pagination. It receives the lastPage fetched and the full array of all pages. Your job is to return the value that should be passed to the next execution of the queryFn. If this function returns undefined or null, the query marks itself as having no more pages, automatically disabling the “load more” functionality.
getNextPageParam: (lastPage, allPages) => {
// If the last page returned no items, stop fetching
if (lastPage.items.length === 0) return undefined;
// Otherwise, return the cursor from the last item
return lastPage.nextCursor;
}
This logic keeps your pagination definition strictly declarative. You define the condition for the end of the data, and the hook manages the state of the infinite list. This separation ensures your UI code remains clean and focused solely on presentation.
c. maxPages, infinite scroll, and UI integration
The maxPages option prevents infinite growth by capping the number of pages stored in the cache. This is vital for performance-critical applications. When integrated with a scroll listener or an IntersectionObserver, you can trigger fetchNextPage() automatically as the user approaches the end of the content.
<script>
$: ({ data, hasNextPage, fetchNextPage } = $query);
</script>
{#each data.pages as page}
{#each page.items as item}
<Item {item} />
{/each}
{/each}
{#if hasNextPage}
<button on:click={() => fetchNextPage()}>Load More</button>
{/if}
The resulting data.pages structure is a nested array. Your UI iterates through the pages and then the items within each page. This structure is preserved by the framework, allowing you to easily handle scenarios where you need to render page separators or perform batch operations on specific data segments.
Complete Example Session
// ============================================
// PART 1: THE CONFIGURATION
// ============================================
const query = createInfiniteQuery({
queryKey: ['projects'],
queryFn: ({ pageParam }) => fetchProjects(pageParam),
initialPageParam: 0,
getNextPageParam: (last) => last.next ?? undefined
});
// ============================================
// PART 2: UI RENDERING
// ============================================
// We flatten the pages to iterate easily
$: items = $query.data?.pages.flatMap(p => p.data) ?? [];
// ============================================
// PART 3: TRIGGERING THE NEXT PAGE
// ============================================
function onScroll() {
if (isAtBottom && $query.hasNextPage) {
$query.fetchNextPage();
}
}
// ============================================
// PART 4: MUTATIONS AND CACHE SYNC
// ============================================
// Deleting an item across multiple pages
function deleteItem(id) {
queryClient.setQueryData(['projects'], (old) => ({
...old,
pages: old.pages.map(p => ({ ...p, data: p.data.filter(i => i.id !== id) }))
}));
}
This sequence illustrates the setup of an infinite query, the flattening of pages for UI consumption, scroll-based triggering, and the advanced task of syncing mutations across the cached page structure.
Quick Reference
Infinite Options
| Option | Purpose |
|---|---|
initialPageParam | Starting value for the cursor/offset |
getNextPageParam | Logic to determine next cursor |
maxPages | Limit pages in cache to save memory |
Query Result Properties
| Property | Description |
|---|---|
data.pages | The array of result sets |
fetchNextPage | Function to load more |
hasNextPage | Boolean: are more pages available? |
isFetchingNextPage | Status for loading spinner |
Best Practices
✅ Do This:
// Define initialPageParam clearly
initialPageParam: 0 // ✅
// Always return undefined to signal end of data
return next ?? undefined; // ✅
// Flatten pages for simple UI loops
$: items = data.pages.flatMap(p => p.items); // ✅
// Use maxPages for memory safety
maxPages: 5 // ✅
❌ Don’t Do This:
// Don't return null if you want to keep fetching
return null; // Signals end of list in some versions // ❌
// Don't fetch the next page in a loop
// (Use user interaction or scroll events) // ❌
// Don't hardcode array indices
// (Always use the provided data.pages structure) // ❌
Common Pitfalls
| Pitfall | Why It Happens | Fix |
|---|---|---|
| Infinite Loop | getNextPageParam logic error | Return undefined on completion |
| Duplicate Data | Bad queryFn or cache key | Ensure keys are unique |
| Stuck Loader | fetchNextPage not triggered | Check hasNextPage status |
| State Mismatch | Direct mutation of pages | Use setQueryData correctly |
Real-World Examples
1. Cursor-based Fetch
getNextPageParam: (last) => last.nextCursor
2. Offset-based Fetch
queryFn: ({ pageParam }) => fetch(`/api?offset=${pageParam}`)
3. Stopping Fetching
if (last.items.length < 20) return undefined;
4. Auto-Loading More
intersectionObserver.observe(target);
5. Cache Size Limit
maxPages: 3
6. Refreshing Infinite Data
query.refetch() // Refetches all pages
7. Page Flattening
const items = data.pages.flatMap(p => p.results)
8. Loading State Logic
{#if $query.isFetchingNextPage} <span>Loading...</span> {/if}
9. Error Handling
{#if $query.isError} <Error /> {/if}
10. Manual Cache Override
queryClient.setQueryData(['posts'], ...)
Visual
Page Stitching Logic
┌──────────────────────────────────────────────┐
│ DATA.PAGES[] │
│ [Page 1] ──► [Page 2] ──► [Page 3] │
│ │ │ │ │
│ ▼ ▼ ▼ │
│ {data: [...]} {data: [...]} {data: [...]} │
│ │
│ Result: Reactive array of page objects │
└──────────────────────────────────────────────┘
The Fetch Loop
┌──────────────────────────────────────────────┐
│ Trigger fetchNextPage() │
│ │ │
│ getNextPageParam() ──► Returns Next Cursor │
│ │ │
│ queryFn(nextCursor) ──► Fetch Page Data │
│ │ │
│ Data.pages.push(newData) ──► Update UI │
└──────────────────────────────────────────────┘
Cache Size Management (maxPages)
┌──────────────────────────────────────────────┐
│ [P1] [P2] [P3] ──► Scroll ──► [P2] [P3] [P4]│
│ │
│ P1 is dropped from memory automatically │
│ to keep resource usage stable. │
└──────────────────────────────────────────────┘
Summary
| Item | Value |
|---|---|
createInfiniteQuery | Paginated state orchestrator |
getNextPageParam | Next fetch logic |
initialPageParam | Starting value |
hasNextPage | Pagination status |
data.pages | Flat data structure |
Key takeaways:
- Use
createInfiniteQueryfor growth. It is the intended primitive for lists that grow as the user scrolls, handling state stitching that is too complex to manage manually. - The page parameter is a contract.
getNextPageParamdetermines the next step; ensuring this logic is sound is the single most important part of implementing infinite scroll correctly. - Flatten for the UI. Always flatten your
data.pagesstructure in a reactive variable to simplify your component’s template logic. - Guard your memory. Use
maxPagesin production environments to prevent the application cache from ballooning during very long user sessions. - Automate the trigger. Integrate with
IntersectionObserverto triggerfetchNextPage()automatically, providing the “infinite” feel that modern users expect.
Remember: Infinite queries move your data fetching from a static request-response model to a dynamic, stream-like lifecycle. By embracing the createInfiniteQuery structure, you offload the complex array management and cursor tracking that otherwise cripples long-form list performance, resulting in a UI that feels both responsive and truly limitless.
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!