TanStack Query Infinite Scroll Error— useInfiniteQuery Fixed [2026]
Also covers: getNextPageParam · initialPageParam (v5) · IntersectionObserver · flatMap pages · hasNextPage false
⚡ Common Errors
// hasNextPage is always false — no more pages load
// OR:
TypeError: data.pages.flat is not a function
// OR (TanStack Query v5):
Error: initialPageParam is required for useInfiniteQuery✅ Correct v5 useInfiniteQuery structure
const { data, fetchNextPage, hasNextPage } = useInfiniteQuery({
queryKey: ["posts"],
queryFn: ({ pageParam }) => fetchPosts({ cursor: pageParam }),
initialPageParam: null, // ← required in v5
getNextPageParam: (lastPage) => lastPage.nextCursor ?? undefined,
})
const allPosts = data?.pages.flatMap(page => page.items) ?? []How useInfiniteQuery Works in TanStack Query v5
Unlike useQuery which stores a single result, useInfiniteQuery stores an array of page results in data.pages . Each time you call fetchNextPage(), TanStack Query calls your queryFn with the next pageParam returned by getNextPageParam . The new page is appended to data.pages and your component re-renders with the full accumulated list.
TanStack Query v5 made initialPageParam a required option. Missing it is the most common upgrade error.
Return nextCursor from getNextPageParam Correctly
hasNextPage false — pagination never advancesYour getNextPageParam function receives the last page response and must return the next cursor or page number. Returning undefined signals no more pages — ensure your API response actually contains the next cursor field.
// Example API response for cursor-based pagination:
{
items: [ /* posts array */ ],
nextCursor: "eyJpZCI6MTAwfQ==", // base64 cursor — null when no more pages
hasMore: true
}
// Example API response for page-number pagination:
{
posts: [ /* posts array */ ],
page: 1,
totalPages: 10
}// Pattern A — cursor-based (recommended for large datasets)
const { data, fetchNextPage, hasNextPage } = useInfiniteQuery({
queryKey: ["posts"],
queryFn: async ({ pageParam }) => {
const url = pageParam
? `/api/posts?cursor=${pageParam}`
: "/api/posts"
const res = await fetch(url)
return res.json()
// Returns: { items: [...], nextCursor: "abc" | null }
},
initialPageParam: null,
getNextPageParam: (lastPage) => {
// ✅ Return cursor if there are more pages, undefined if not
return lastPage.nextCursor ?? undefined
},
})
// Pattern B — page number based
const { data, fetchNextPage, hasNextPage } = useInfiniteQuery({
queryKey: ["posts"],
queryFn: async ({ pageParam }) => {
const res = await fetch(`/api/posts?page=${pageParam}&limit=10`)
return res.json()
// Returns: { posts: [...], page: 1, totalPages: 10 }
},
initialPageParam: 1,
getNextPageParam: (lastPage) => {
// ✅ Return next page number, or undefined if on last page
return lastPage.page < lastPage.totalPages
? lastPage.page + 1
: undefined
},
})Trigger fetchNextPage with IntersectionObserver
Complete infinite scroll implementationThe most reliable way to trigger fetchNextPage is to observe a sentinel element at the bottom of the list. When it enters the viewport, load the next page.
import { useEffect, useRef } from "react"
export function useIntersectionObserver(
callback: () => void,
options: IntersectionObserverInit = { threshold: 0.1 }
) {
const ref = useRef<HTMLDivElement>(null)
useEffect(() => {
const el = ref.current
if (!el) return
const observer = new IntersectionObserver(([entry]) => {
if (entry.isIntersecting) callback()
}, options)
observer.observe(el)
return () => observer.disconnect()
}, [callback, options])
return ref
}"use client"
import { useInfiniteQuery } from "@tanstack/react-query"
import { useCallback } from "react"
import { useIntersectionObserver } from "@/hooks/use-intersection-observer"
async function fetchPosts({ pageParam }: { pageParam: string | null }) {
const url = pageParam
? `/api/posts?cursor=${pageParam}`
: "/api/posts"
const res = await fetch(url)
if (!res.ok) throw new Error("Failed to fetch posts")
return res.json() as Promise<{ items: Post[]; nextCursor: string | null }>
}
export function PostList() {
const {
data,
fetchNextPage,
hasNextPage,
isFetchingNextPage,
isLoading,
isError,
} = useInfiniteQuery({
queryKey: ["posts"],
queryFn: fetchPosts,
initialPageParam: null,
getNextPageParam: (lastPage) => lastPage.nextCursor ?? undefined,
staleTime: 5 * 60 * 1000,
})
// Memoised callback — fetchNextPage is stable but wrap anyway
const loadMore = useCallback(() => {
if (hasNextPage && !isFetchingNextPage) {
fetchNextPage()
}
}, [hasNextPage, isFetchingNextPage, fetchNextPage])
// Attach observer to sentinel element
const sentinelRef = useIntersectionObserver(loadMore)
// Flatten all pages into one array
const posts = data?.pages.flatMap(page => page.items) ?? []
if (isLoading) return <div>Loading posts...</div>
if (isError) return <div>Error loading posts</div>
return (
<div>
{posts.map(post => (
<div key={post.id} className="border rounded p-4 mb-3">
<h2>{post.title}</h2>
<p>{post.content}</p>
</div>
))}
{/* Sentinel — triggers fetchNextPage when visible */}
<div ref={sentinelRef} className="h-4" />
{isFetchingNextPage && <div>Loading more...</div>}
{!hasNextPage && posts.length > 0 && <div>No more posts</div>}
</div>
)
}Flatten Pages into a Single Item Array
TypeError: Cannot read properties of undefinedA very common mistake is trying to map over data.pages directly, or using .flat() instead of .flatMap() . You must use flatMap to access the items array inside each page.
// data.pages shape:
// [
// { items: [post1, post2, post3], nextCursor: "abc" }, ← page 1
// { items: [post4, post5, post6], nextCursor: "def" }, ← page 2
// { items: [post7, post8], nextCursor: null }, ← page 3
// ]
// ❌ Wrong — maps over page OBJECTS, not items
const posts = data?.pages.map(page => page) // array of page objects
// ❌ Wrong — .flat() flattens one level but page is an object not array
const posts = data?.pages.flat() // still array of page objects
// ✅ Correct — flatMap extracts items from each page
const posts = data?.pages.flatMap(page => page.items) ?? []
// ✅ With TypeScript — ensure type safety
type PostsPage = { items: Post[]; nextCursor: string | null }
const posts: Post[] = data?.pages.flatMap((page: PostsPage) => page.items) ?? []Fix hasNextPage Always False
getNextPageParam always returning undefinedIf hasNextPage is always false , debug your getNextPageParam by logging the last page and checking what it contains.
const { data, hasNextPage } = useInfiniteQuery({
queryKey: ["posts"],
queryFn: async ({ pageParam }) => {
const res = await fetch(`/api/posts?cursor=${pageParam ?? ""}`)
const data = await res.json()
console.log("Page data:", data) // ← check what your API returns
console.log("nextCursor:", data.nextCursor) // ← is this actually set?
return data
},
initialPageParam: null,
getNextPageParam: (lastPage, allPages) => {
console.log("getNextPageParam called:", lastPage) // ← check the last page
// Common mistakes:
// ❌ return lastPage.next_cursor // wrong field name (underscore)
// ❌ return lastPage.data.nextCursor // wrong nesting
// ✅ return lastPage.nextCursor ?? undefined // correct
return lastPage.nextCursor ?? undefined
},
})
console.log("hasNextPage:", hasNextPage) // should be true when more pages existOpen React Query DevTools (add ReactQueryDevtools to your provider) and inspect the infinite query. It shows all pages, the current pageParam, and whether hasNextPage is true — invaluable for debugging.
Handle the v5 initialPageParam Requirement
Upgrading from TanStack Query v4 — breaking changeTanStack Query v5 requires initialPageParam explicitly. In v4, pageParam started as undefined by default. In v5, you must declare the initial value.
// ❌ v4 pattern — pageParam started as undefined
const { data } = useInfiniteQuery({
queryKey: ["posts"],
queryFn: ({ pageParam = null }) => fetchPosts(pageParam), // default in queryFn
getNextPageParam: (lastPage) => lastPage.nextCursor,
})
// ✅ v5 pattern — initialPageParam is required
const { data } = useInfiniteQuery({
queryKey: ["posts"],
queryFn: ({ pageParam }) => fetchPosts(pageParam), // no default needed
initialPageParam: null, // ← declare here
getNextPageParam: (lastPage) => lastPage.nextCursor ?? undefined,
})
// Also changed in v5:
// - data.pages is now typed correctly with TypeScript
// - getNextPageParam and getPreviousPageParam receive (lastPage, allPages, lastPageParam)
// - cacheTime renamed to gcTimeimport { useInfiniteQuery } from "@tanstack/react-query"
type Post = { id: string; title: string; content: string }
type PostsPage = { items: Post[]; nextCursor: string | null }
function useInfinitePosts() {
return useInfiniteQuery<PostsPage, Error, PostsPage, string[], string | null>({
queryKey: ["posts"],
queryFn: async ({ pageParam }) => {
const url = pageParam ? `/api/posts?cursor=${pageParam}` : "/api/posts"
const res = await fetch(url)
return res.json()
},
initialPageParam: null,
getNextPageParam: (lastPage) => lastPage.nextCursor,
staleTime: 5 * 60 * 1000,
})
}
// Usage:
function PostList() {
const { data, fetchNextPage, hasNextPage, isFetchingNextPage } = useInfinitePosts()
const posts = data?.pages.flatMap(page => page.items) ?? []
// ...
}Prevention
- Always set initialPageParam explicitly in v5 — use null for cursor-based, 1 for page-number based
- Log your API response inside queryFn during development to confirm the nextCursor field name and location
- Use flatMap(page => page.items) to flatten pages — never .flat() or iterating pages directly
- Return undefined (not null) from getNextPageParam when there are no more pages — null is treated as a valid pageParam
- Use IntersectionObserver for scroll detection — more reliable and performant than scroll event listeners
- Install ReactQueryDevtools and inspect infinite query state to debug hasNextPage and page counts
Frequently Asked Questions
What is useInfiniteQuery in TanStack Query?+−
Why is hasNextPage always false in my useInfiniteQuery?+−
What is getNextPageParam in TanStack Query?+−
Why do I need initialPageParam in TanStack Query v5?+−
How do I flatten useInfiniteQuery pages into a flat array?+−
What is IntersectionObserver and why do I need it for infinite scroll?+−
Need Expert Help?
We Build Infinite Scroll with TanStack Query
Softplix engineers implement cursor-based pagination, infinite scroll, and optimistic UIs with TanStack Query v5. Let us help.
Talk to an Engineer