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

window-focus-refetching.md

95 lines3.6 KB

1---
2id: window-focus-refetching
3title: Window Focus Refetching
4---
5​
6If a user leaves your application and returns to stale data, **React 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```js
11//
12const queryClient = new QueryClient({
13 defaultOptions: {
14 queries: {
15 refetchOnWindowFocus: false,
16 },
17 },
18})
19​
20function App() {
21 return <QueryClientProvider client={queryClient}>...</QueryClientProvider>
23```
24​
25#### Disabling Per-Query
26​
27```js
28useQuery('todos', fetchTodos, { refetchOnWindowFocus: false })
29```
30​
31## Custom Window Focus Event
32​
33In rare circumstances, you may want to manage your own window focus events that trigger React Query to revalidate. To do this, React 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:
34​
35```js
36focusManager.setEventListener(handleFocus => {
37 // Listen to visibilitychange and focus
38 if (typeof window !== 'undefined' && window.addEventListener) {
39 window.addEventListener('visibilitychange', handleFocus, false)
40 window.addEventListener('focus', handleFocus, false)
41 }
42​
43 return () => {
44 // Be sure to unsubscribe if a new handler is set
45 window.removeEventListener('visibilitychange', handleFocus)
46 window.removeEventListener('focus', handleFocus)
47 }
48})
49```
50​
51## Ignoring Iframe Focus Events
52​
53A 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:
54​
55```js
56import { focusManager } from 'react-query'
57import onWindowFocus from './onWindowFocus' // The gist above
58​
59focusManager.setEventListener(onWindowFocus) // Boom!
60```
61​
62## Managing Focus in React Native
63​
64Instead 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":
65​
66```js
67import { AppState } from 'react-native'
68import { focusManager } from 'react-query'
69​
70focusManager.setEventListener(handleFocus => {
71 const subscription = AppState.addEventListener('change', state => {
72 handleFocus(state === 'active')
73 })
74​
75 return () => {
76 subscription.remove()
77 }
78})
79```
80​
81## Managing focus state
82​
83```js
84import { focusManager } from 'react-query'
85​
86// Override the default focus state
87focusManager.setFocused(true)
88​
89// Fallback to the default focus check
90focusManager.setFocused(undefined)
91```
92​
93## Pitfalls & Caveats
94​
95Some 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.