TanStack QueryReact QueryError Fix2026 Updated

TanStack Query Not Refetching— staleTime, Polling & Invalidation [2026]

Also covers: staleTime · refetchOnWindowFocus · refetchInterval · manual refetch · invalidateQueries after mutation

January 20266 min readTanStack Query v5 · React

⚡ The Symptom

Error
// Data never updates after first fetch
// Switching tabs doesn't trigger a refetch
// Mutations complete but query shows stale data

✅ Key settings that control refetching

useQuery refetch options
useQuery({
  queryKey: ["posts"],
  queryFn: fetchPosts,
  staleTime: 60_000,            // data is fresh for 1 min
  refetchOnWindowFocus: true,   // refetch when tab regains focus
  refetchInterval: false,       // no polling by default
})

Why TanStack Query Stops Refetching

TanStack Query refetches in the background when certain triggers fire: window focus, component remount, network reconnect, or manual invalidation. These refetches only happen when the data is stale . If staleTime is set very high or Infinity, data is never considered stale and background refetches never trigger.

1

Understand and Set staleTime Correctly

Data never refetches — staleTime too high
2 min
staleTime — choose the right value
// staleTime: 0 (default) — always stale, refetches on every focus/mount
// staleTime: 60_000 — fresh for 1 minute
// staleTime: Infinity — never stale, never background-refetches

// Per-query staleTime
const { data } = useQuery({
  queryKey: ["posts"],
  queryFn: fetchPosts,
  staleTime: 5 * 60 * 1000,   // 5 minutes — good for slowly-changing data
})

// Global default staleTime in QueryClient
const queryClient = new QueryClient({
  defaultOptions: {
    queries: {
      staleTime: 60 * 1000,   // 1 minute for all queries by default
    },
  },
})

Use staleTime: Infinity only for truly static data (config, translations). For user data, prices, or anything that changes, use a specific time value so background refetches keep the UI fresh.

2

Enable refetchOnWindowFocus

Data stays stale after switching tabs
1 min
refetchOnWindowFocus options
// Global — enabled by default, but you may have disabled it
const queryClient = new QueryClient({
  defaultOptions: {
    queries: {
      refetchOnWindowFocus: true,    // default — true
      refetchOnMount: true,          // default — true
      refetchOnReconnect: true,      // default — true
    },
  },
})

// Per-query override
const { data } = useQuery({
  queryKey: ["live-prices"],
  queryFn: fetchPrices,
  staleTime: 0,                   // always stale
  refetchOnWindowFocus: true,     // refetch when user returns to tab
})

// Set to 'always' to refetch even when data is not stale
const { data } = useQuery({
  queryKey: ["notifications"],
  queryFn: fetchNotifications,
  refetchOnWindowFocus: "always",   // always refetch on focus, even if fresh
})
3

Use refetchInterval for Polling

Live data that must update automatically
2 min
Polling — refetchInterval
// Poll every 30 seconds
const { data: liveData } = useQuery({
  queryKey: ["live-dashboard"],
  queryFn: fetchDashboardData,
  refetchInterval: 30_000,            // poll every 30 seconds
  refetchIntervalInBackground: true,  // keep polling even in background tab
})

// Conditional polling — stop when data meets a condition
const { data: job } = useQuery({
  queryKey: ["job", jobId],
  queryFn: () => fetchJob(jobId),
  refetchInterval: (query) => {
    // Stop polling when job is complete
    if (query.state.data?.status === "completed") return false
    return 5000   // poll every 5 seconds while running
  },
})
4

Manually Trigger a Refetch

Button click / user action triggers fresh fetch
2 min
Manual refetch with refetch()
"use client"

import { useQuery } from "@tanstack/react-query"

export function DataPanel() {
  const { data, isFetching, refetch } = useQuery({
    queryKey: ["stats"],
    queryFn: fetchStats,
  })

  return (
    <div>
      <div className="flex items-center gap-2">
        <h2>Statistics</h2>
        {isFetching && <span className="text-xs text-gray-400">Refreshing...</span>}
        <button
          onClick={() => refetch()}   // ← triggers an immediate refetch
          disabled={isFetching}
        >
          Refresh
        </button>
      </div>
      <Stats data={data} />
    </div>
  )
}
5

Invalidate Queries After Mutations

Mutation completes but list shows stale data
3 min
useMutation + invalidateQueries
import { useMutation, useQueryClient } from "@tanstack/react-query"

export function CreatePostButton() {
  const queryClient = useQueryClient()

  const mutation = useMutation({
    mutationFn: (newPost: { title: string; content: string }) =>
      fetch("/api/posts", {
        method: "POST",
        body: JSON.stringify(newPost),
      }).then(r => r.json()),

    onSuccess: () => {
      // ✅ Invalidate the posts list — triggers background refetch
      queryClient.invalidateQueries({ queryKey: ["posts"] })

      // ✅ Invalidate multiple related queries
      queryClient.invalidateQueries({ queryKey: ["posts"] })
      queryClient.invalidateQueries({ queryKey: ["user-stats"] })
    },

    onError: (error) => {
      console.error("Failed to create post:", error)
    },
  })

  return (
    <button
      onClick={() => mutation.mutate({ title: "New Post", content: "..." })}
      disabled={mutation.isPending}
    >
      {mutation.isPending ? "Creating..." : "Create Post"}
    </button>
  )
}

Prevention

Frequently Asked Questions

Why does TanStack Query not refetch when I switch tabs?+
Refetch on window focus is enabled by default in TanStack Query. If it is not firing, either you have set refetchOnWindowFocus: false in your query or global config, or staleTime: Infinity which prevents refetching even on focus. Check your QueryClient defaultOptions.
What is staleTime in TanStack Query?+
staleTime is how long (in milliseconds) a query's data is considered fresh. During this time, queries will not refetch even if the window focuses or the component remounts. After the staleTime expires, the data is 'stale' and a background refetch is triggered on the next observer event.
How do I make TanStack Query poll data every 30 seconds?+
Set refetchInterval: 30000 in your useQuery options. The query will refetch every 30 seconds in the background. Combine with refetchIntervalInBackground: true to keep polling even when the user's tab is in the background.
What is the difference between refetch() and invalidateQueries()?+
refetch() triggers a refetch for the specific query instance immediately. invalidateQueries() marks matching queries as stale and triggers a background refetch on any active observer — it is broader and works across components. Use refetch() for one-off user-triggered fetches; use invalidateQueries() after mutations.
Why is TanStack Query not refetching after a mutation?+
After a mutation that changes data, you must invalidate the relevant queries using queryClient.invalidateQueries({ queryKey: ['posts'] }). TanStack Query does not know when your server data changes — you must tell it by invalidating the cache keys that cover the affected data.
Can TanStack Query refetch in the background without showing a loading state?+
Yes. Background refetches don't set isLoading to true — they use isFetching instead. isLoading is only true when there is no cached data at all. Use isFetching to show a subtle refresh indicator while the background refetch runs.

Need Expert Help?

We Build Data-Driven UIs with TanStack Query

Softplix engineers implement TanStack Query with optimal caching, invalidation, and real-time refresh strategies. Let us help.

Talk to an Engineer