Refetch Configuration Options
What you'll learn: How to fine-tune when TanStack Query automatically refetches your data using configuration flags.
You've learned that TanStack Query can automatically refetch on window focus, network reconnect, and through intervals. Now let's see how to control these behaviors with three key options.
The Configuration Trio
refetchOnMount controls whether a query refetches when a component using it mounts. By default, it refetches if the data is stale. You can set it to true (always refetch), false (never refetch), or "always" (refetch even if data is fresh).
refetchOnWindowFocus determines if the query refetches when the browser tab regains focus. Default is true, but you can disable it entirely with false or force it with "always".
refetchOnReconnect controls refetching when the network reconnects after being offline. Like the others, it defaults to true but respects staleness—set false to disable or "always" to force.
Practical Example
const { data } = useQuery({
queryKey: ['user', userId],
queryFn: fetchUser,
staleTime: 60000, // Data stays fresh for 1 minute
refetchOnMount: false, // Don't refetch when component mounts
refetchOnWindowFocus: 'always', // Always refetch on tab focus
refetchOnReconnect: true // Refetch if data is stale on reconnect
});
Think of It Like This
Imagine your data is a newspaper. refetchOnMount asks "Should I check for a new edition when I walk into the room?" refetchOnWindowFocus asks "Should I check when I look back at the paper?" refetchOnReconnect asks "Should I check when the delivery service comes back online?"
Key Takeaway: Use refetchOnMount, refetchOnWindowFocus, and refetchOnReconnect to balance data freshness with network efficiency—enabling them keeps data current, while disabling reduces unnecessary requests for stable data.