Maaz Zindani

Loading the index…

↑↓ move↵ openesc close4072 pages
Next.js and React

TanStack Query useInfiniteQuery reloads every page again and again

Errorthe list flashes and reloads when you switch back to the browser tab

Short answer

An infinite query is one cached entry with many pages. When it goes stale, a refetch loads every page again, one after the other, starting with the first. Stale happens by default on mount, window focus and reconnect. Raise staleTime, guard fetchNextPage, and return undefined from getNextPageParam on the last page.

  • Applies to TanStack Query v5, React 19
  • Updated
  • By Maaz Zindani, Senior Software Engineer

Fix it fast

  1. 1Find out which cause you have

    Open the network tab, switch to another tab and back. If the requests for every page repeat, the cause is the stale refetch. If requests repeat while you scroll, look at the fetchNextPage guard.

    // temporary: log why the hook is fetching
    const q = useInfiniteQuery({ /* options */ });
    console.log(q.isFetching, q.isFetchingNextPage, q.hasNextPage);
  2. 2Match what you see, then jump to its fix

    1. 1Requests repeat after you return to the tab, remount the screen or regain networkThe query is stale, so focus, mount and reconnect trigger a refetch of all pagesFix
    2. 2Scrolling near the end fires several requests, and some page data appears to be overwrittenfetchNextPage is called while another fetch is still runningFix
    3. 3Loading more keeps going after the data has ended, or hasNextPage stays truegetNextPageParam never returns undefined on the last pageFix

What does the error look like?

  • the list flashes and reloads when you switch back to the browser tab
  • the network tab shows page 1, 2, 3 requested again one after another
  • new page data replaces older data while scrolling

Cause 1 of 3

The query is stale, so focus, mount and reconnect trigger a refetch of all pages

1Check

TanStack Query treats cached data as stale by default. Stale queries refetch when a new instance mounts, when the window is refocused, and when the network reconnects. For an infinite query each group is then fetched sequentially, starting from the first.

grep -rn "staleTime\|refetchOnWindowFocus" src/

2Fix

Give the query a staleTime. Infinity means no refetch until you invalidate it.

useInfiniteQuery({
  queryKey: ['posts'],
  queryFn: ({ pageParam }) => fetchPosts(pageParam),
  initialPageParam: 0,
  getNextPageParam: (last) => last.nextCursor,
  staleTime: 5 * 60 * 1000, // or Infinity
});

3Verify

Switch tabs and back. No new requests appear until the stale time has passed.

// network tab: filter by /posts and switch tabs

Confirmed by tanstack.com

Did this fix it?

Cause 2 of 3

fetchNextPage is called while another fetch is still running

1Check

There can be only one ongoing fetch per infinite query. The guide warns that calling fetchNextPage during an ongoing fetch risks overwriting data refreshes.

grep -rn "fetchNextPage" src/

2Fix

Call fetchNextPage only when there is a next page and nothing is fetching. Use isFetchingNextPage to tell loading more apart from a background refresh.

const { fetchNextPage, hasNextPage, isFetching } = q;

useEffect(() => {
  if (inView && hasNextPage && !isFetching) {
    fetchNextPage();
  }
}, [inView, hasNextPage, isFetching, fetchNextPage]);

3Verify

Scroll to the end. One request per page appears in the network tab.

// network tab: one request per scroll step

Confirmed by tanstack.com

Did this fix it?

Cause 3 of 3

getNextPageParam never returns undefined on the last page

1Check

hasNextPage is true when getNextPageParam returns something other than null or undefined. A function that always returns a number, such as page + 1, never says that the list ended.

console.log(q.hasNextPage, q.data?.pages.at(-1))

2Fix

Return undefined when the last page signals the end, for example when it holds no items or has no next cursor.

getNextPageParam: (lastPage, allPages) =>
  lastPage.items.length === 0 ? undefined : allPages.length + 1,

3Verify

Scroll to the last page. hasNextPage turns false and no more requests are sent.

console.log(q.hasNextPage)

Confirmed by tanstack.com

Did this fix it?

How do I stop it coming back?

  • Decide a staleTime for every list query instead of living with the default.
  • Put the has-next-page and not-fetching checks into one reusable scroll hook.
  • Keep getNextPageParam free of side effects: it only reads the last page.

Sources

How was this page made?

I drafted this page with AI assistance from the official documents listed under Sources. Every cause above names the document that confirms it. I have not reproduced this fix on a machine of my own yet, so read it as documented guidance, not a test report. Found a mistake? Tell me.

Which stack is behind this page?

Projects of mine built on the same technologies:

Related fixes

Web apps

useQuery returns data as undefined

TypeError: Cannot read properties of undefined (reading 'map')

data is undefined until the query succeeds, so check isPending and isError first.

3 causes, each with a fix

Next step

Want this handled for good?

I look after servers, apps and releases end to end. Tell me what keeps breaking.