TanStack QueryInfinite ScrollError Fix2026 Updated

TanStack Query Infinite Scroll Error— useInfiniteQuery Fixed [2026]

Also covers: getNextPageParam · initialPageParam (v5) · IntersectionObserver · flatMap pages · hasNextPage false

January 20268 min readTanStack Query v5 · React · TypeScript

⚡ Common Errors

Error
// 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

Minimal working useInfiniteQuery (v5)
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.

1

Return nextCursor from getNextPageParam Correctly

hasNextPage false — pagination never advances
5 min

Your 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.

API response shape — what your server returns
// 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
}
getNextPageParam — cursor-based and page-number patterns
// 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
  },
})
2

Trigger fetchNextPage with IntersectionObserver

Complete infinite scroll implementation
8 min

The 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.

hooks/use-intersection-observer.ts
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
}
components/post-list.tsx — complete infinite scroll
"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>
  )
}
3

Flatten Pages into a Single Item Array

TypeError: Cannot read properties of undefined
2 min

A 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.

Correct page flattening
// 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) ?? []
4

Fix hasNextPage Always False

getNextPageParam always returning undefined
3 min

If hasNextPage is always false , debug your getNextPageParam by logging the last page and checking what it contains.

Debug getNextPageParam
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 exist

Open 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.

5

Handle the v5 initialPageParam Requirement

Upgrading from TanStack Query v4 — breaking change
2 min

TanStack Query v5 requires initialPageParam explicitly. In v4, pageParam started as undefined by default. In v5, you must declare the initial value.

v4 → v5 migration
// ❌ 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 gcTime
Complete TypeScript-typed useInfiniteQuery (v5)
import { 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

Frequently Asked Questions

What is useInfiniteQuery in TanStack Query?+
useInfiniteQuery is a TanStack Query hook for paginated or cursor-based data loading. Unlike useQuery which holds a single result, useInfiniteQuery stores multiple pages of results and provides fetchNextPage to load more. It is the standard way to implement infinite scroll in React.
Why is hasNextPage always false in my useInfiniteQuery?+
hasNextPage is derived from getNextPageParam — it is true only when getNextPageParam returns a non-undefined, non-null value. If your getNextPageParam always returns undefined (even when there are more pages), hasNextPage will always be false. Check that your API response includes a nextCursor or nextPage field and that you are reading it correctly.
What is getNextPageParam in TanStack Query?+
getNextPageParam is a function that receives the last page of data (and all pages so far) and must return the cursor or page number for the next page. If there are no more pages, return undefined or null. The return value is passed as the pageParam argument to your queryFn on the next fetch.
Why do I need initialPageParam in TanStack Query v5?+
TanStack Query v5 made initialPageParam a required option for useInfiniteQuery. In v4, the first fetch had pageParam as undefined by default. In v5, you must explicitly set initialPageParam: 0 (for page-based) or initialPageParam: null (for cursor-based). Not setting this causes a TypeScript error and incorrect first-page fetching.
How do I flatten useInfiniteQuery pages into a flat array?+
Use data.pages.flatMap(page => page.items) to combine all page results into a single array. data.pages is an array of page responses — each page has your API's response shape. Access items within each page using the appropriate field name from your API (e.g. .items, .data, .results, .posts).
What is IntersectionObserver and why do I need it for infinite scroll?+
IntersectionObserver is a browser API that notifies you when an element becomes visible in the viewport. For infinite scroll, you attach it to a sentinel element at the bottom of your list. When the sentinel becomes visible, you call fetchNextPage to load the next batch of items. It is more performant than scroll event listeners.

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