Skip to content
Tutorials Center
My learning

Topics

Lesson 17 of 38 ยท Caching and Staleness

Refetch Triggers: Focus, Reconnect and Mount

Learn which events make stale queries refetch automatically: window focus, network reconnect, component mount and interval. Tune them and simulate them with focusManager.

A stale query does not refetch by itself just because time passed. Query is lazy: it waits for an event that suggests the user might look at the data, and then it refreshes. These events are the refetch triggers. They are why a TanStack Query app feels live: switch back to the tab and the list quietly updates, with no code from you. They are also why a request sometimes appears "for no reason" until you know the list.

The three automatic triggers

Each trigger is a useQuery option (or a QueryClient default) with these possible values:

  • true (default): refetch if the data is stale.
  • false: never refetch on this trigger.
  • "always": refetch even if the data is fresh.
  • a function (query) => true | false | "always".
Option Event Default
refetchOnMount A new observer mounts for the key true
refetchOnWindowFocus The browser tab or window regains focus true
refetchOnReconnect The network connection returns true

Because the default staleTime is 0, data is always stale, so with defaults every one of these events refetches. Raise staleTime and the triggers become quiet for fresh data, as shown in Stale Time and Garbage Collection Time.

There is a fourth, opt-in trigger, refetchInterval, which refetches on a timer. It has its own lesson: Polling and Background Refetching.

Simulating a focus change

A TryIt sandbox cannot switch your browser tab for you, but Query exposes the same machinery it uses: the focusManager. focusManager.setFocused(true) behaves exactly like the window regaining focus. Click the buttons to "leave" and "return" to the tab.

Window focus refetching

Press "Leave" then "Return". The first score (stale, trigger on) and the last one ("always") refresh. The one with a 60-second staleTime is still fresh, so it does not. The one with the trigger disabled never does. The ["score", ...] keys contain the option values only so the four examples do not share a cache entry.

Why a focus refetch is usually good

Users leave tabs open for hours. Without a refresh, the first thing they see on return is hours-old data. A focus refetch is cheap (one request per stale query that is on screen), invisible (old data stays while the new one loads) and makes dashboards and lists feel alive. Turn it off for data where a refetch has a cost or is distracting:

JavaScript
const queryClient = new QueryClient({
  defaultOptions: { queries: { refetchOnWindowFocus: false } },
});

Typical reasons: forms that load initial values (a background refetch could replace data under the user's cursor), expensive endpoints, or data that cannot change.

Form pitfalls

If a form is initialized from query data, a window-focus refetch that changes data must not wipe what the user typed. Copy the data into form state once, or use refetchOnWindowFocus: false, staleTime: Infinity for that edit query.

refetchOnMount

When a component mounts, Query looks at the cache for its key. With the default true, stale data is refetched in the background while the cached value renders at once. With false, mounting never triggers a fetch (the first-ever mount still does, since there is no data). With "always", mount always refetches. This is the trigger behind the instant-yet-fresh feel of navigating back to a page.

Reconnect and the online manager

refetchOnReconnect fires when the browser reports that the network is back. Query tracks that through the onlineManager. If you ever need to override it (for example in React Native, or to simulate going offline), you can:

JavaScript
import { onlineManager } from "@tanstack/react-query";

onlineManager.setOnline(false);   // queries pause
onlineManager.setOnline(true);    // and resume, refetching stale ones

While offline, queries do not fail; they become paused (fetchStatus: "paused") and continue when the connection returns. How this interacts with networkMode is covered in Retries and Error Handling.

Focus in other environments

In the browser, Query listens to the visibilitychange event. In React Native there is no such event, so you give Query your own signal, using AppState:

JavaScript
import { AppState } from "react-native";
import { focusManager } from "@tanstack/react-query";

AppState.addEventListener("change", (status) => {
  focusManager.setFocused(status === "active");
});

focusManager.setEventListener lets you replace the default listener entirely, which is also how tests and embedded webviews provide their own focus source.

Debugging an unexpected request

If a request starts when you did not expect one, check in this order:

  1. Is the data stale? With staleTime: 0 it always is. This explains most surprises.
  2. Which trigger fired? Focus, mount, reconnect, or an interval? DevTools (see DevTools) shows a query flipping to fetching.
  3. Did the key change? A new key is a new query and fetches regardless of staleness.
  4. Was it invalidated? Another part of the app may call invalidateQueries.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. With default options, what happens to a stale query when the window regains focus?

    refetchOnWindowFocus defaults to true, and stale data is refetched.
  2. 2. What does refetchOnWindowFocus: 'always' do?

    'always' ignores staleTime for that trigger.
  3. 3. How can you simulate the tab regaining focus in a demo or a test?

    focusManager is the same machinery Query uses to track focus.
  4. 4. A form is filled from query data and users lose their input after switching tabs. What is a likely cause?

    Copy data into form state once, or disable the focus refetch (and use a long staleTime) for edit queries.

Summary

  • Stale queries refetch on refetchOnMount, refetchOnWindowFocus and refetchOnReconnect; all default to true.
  • Each option accepts true, false, "always" or a function.
  • Fresh data is left alone, so a larger staleTime makes triggers quiet.
  • focusManager and onlineManager are the signals behind the triggers, and you can drive them manually.
  • When a request surprises you, check staleness, the trigger, the key and invalidation.

Next: Polling and Background Refetching