Skip to content
Source
Sign inSign up
TanStack/query
Open History to see the last commit

window-focus-refetching.md

124 lines4.0 KB

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>
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 }
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.