Open History to see the last commit
1---
2id: window-focus-refetching
3title: Window Focus Refetching
4---
5β
6If a user leaves your application and returns and the query data is stale, **TanStack Query automatically requests fresh data for you in the background**. You can disable this globally or per-query using the `refetchOnWindowFocus` option:
7β
8#### Disabling Globally
9β
10[//]: # 'Example'
11β
12```tsx
13//
14const queryClient = new QueryClient({
15 defaultOptions: {
16 queries: {
17 refetchOnWindowFocus: false, // default: true
18 },
19 },
20})
21β
22function App() {
23 return <QueryClientProvider client={queryClient}>...</QueryClientProvider>
24}
25```
26β
27[//]: # 'Example'
28β
29#### Disabling Per-Query
30β
31[//]: # 'Example2'
32β
33```tsx
34useQuery({
35 queryKey: ['todos'],
36 queryFn: fetchTodos,
37 refetchOnWindowFocus: false,
38})
39```
40β
41[//]: # 'Example2'
42β
43## Custom Window Focus Event
44β
45In rare circumstances, you may want to manage your own window focus events that trigger TanStack Query to revalidate. To do this, TanStack Query provides a `focusManager.setEventListener` function that supplies you the callback that should be fired when the window is focused and allows you to set up your own events. When calling `focusManager.setEventListener`, the previously set handler is removed (which in most cases will be the default handler) and your new handler is used instead. For example, this is the default handler:
46β
47[//]: # 'Example3'
48β
49```tsx
50focusManager.setEventListener((handleFocus) => {
51 // Listen to visibilitychange and focus
52 if (typeof window !== 'undefined' && window.addEventListener) {
53 window.addEventListener('visibilitychange', handleFocus, false)
54 window.addEventListener('focus', handleFocus, false)
55 }
56β
57 return () => {
58 // Be sure to unsubscribe if a new handler is set
59 window.removeEventListener('visibilitychange', handleFocus)
60 window.removeEventListener('focus', handleFocus)
61 }
62})
63```
64β
65[//]: # 'Example3'
66β
67## Ignoring Iframe Focus Events
68β
69A great use-case for replacing the focus handler is that of iframe events. Iframes present problems with detecting window focus by both double-firing events and also firing false-positive events when focusing or using iframes within your app. If you experience this, you should use an event handler that ignores these events as much as possible. I recommend [this one](https://gist.github.com/tannerlinsley/1d3a2122332107fcd8c9cc379be10d88)! It can be set up in the following way:
70β
71[//]: # 'Example4'
72β
73```tsx
74import { focusManager } from '@tanstack/react-query'
75import onWindowFocus from './onWindowFocus' // The gist above
76β
77focusManager.setEventListener(onWindowFocus) // Boom!
78```
79β
80[//]: # 'Example4'
81[//]: # 'ReactNative'
82β
83## Managing Focus in React Native
84β
85Instead of event listeners on `window`, React Native provides focus information through the [`AppState` module](https://reactnative.dev/docs/appstate#app-states). You can use the `AppState` "change" event to trigger an update when the app state changes to "active":
86β
87```tsx
88import { AppState } from 'react-native'
89import { focusManager } from '@tanstack/react-query'
90β
91function onAppStateChange(status: AppStateStatus) {
92 if (Platform.OS !== 'web') {
93 focusManager.setFocused(status === 'active')
94 }
95}
96β
97useEffect(() => {
98 const subscription = AppState.addEventListener('change', onAppStateChange)
99β
100 return () => subscription.remove()
101}, [])
102```
103β
104[//]: # 'ReactNative'
105β
106## Managing focus state
107β
108[//]: # 'Example5'
109β
110```tsx
111import { focusManager } from '@tanstack/react-query'
112β
113// Override the default focus state
114focusManager.setFocused(true)
115β
116// Fallback to the default focus check
117focusManager.setFocused(undefined)
118```
119β
120[//]: # 'Example5'
121β
122## Pitfalls & Caveats
123β
124Some browser internal dialogue windows, such as spawned by `alert()` or file upload dialogues (as created by `<input type="file" />`) might also trigger focus refetching after they close. This can result in unwanted side effects, as the refetching might trigger component unmounts or remounts before your file upload handler is executed. See [this issue on GitHub](https://github.com/tannerlinsley/react-query/issues/2960) for background and possible workarounds.