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

window-focus-refetching.md

111 lines3.4 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
52 if (typeof window !== 'undefined' && window.addEventListener) {
53 const visibilitychangeHandler = () => {
54 handleFocus(document.visibilityState === 'visible')
55 }
56 window.addEventListener('visibilitychange', visibilitychangeHandler, false)
57 return () => {
58 // Be sure to unsubscribe if a new handler is set
59 window.removeEventListener('visibilitychange', visibilitychangeHandler)
60 }
61 }
62})
63```
64​
65[//]: # 'Example3'
66[//]: # 'ReactNative'
67​
68## Managing Focus in React Native
69​
70Instead 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":
71​
72```tsx
73import { AppState } from 'react-native'
74import { focusManager } from '@tanstack/react-query'
75​
76function onAppStateChange(status: AppStateStatus) {
77 if (Platform.OS !== 'web') {
78 focusManager.setFocused(status === 'active')
79 }
81​
82useEffect(() => {
83 const subscription = AppState.addEventListener('change', onAppStateChange)
84​
85 return () => subscription.remove()
86}, [])
87```
88​
89[//]: # 'ReactNative'
90​
91## Managing focus state
92​
93[//]: # 'Example4'
94​
95```tsx
96import { focusManager } from '@tanstack/react-query'
97​
98// Override the default focus state
99focusManager.setFocused(true)
100​
101// Fallback to the default focus check
102focusManager.setFocused(undefined)
103```
104​
105[//]: # 'Example4'
106​
107## Troubleshooting
108​
109If stale queries do not refetch when you return to a tab, check whether **Emulate a focused page** is enabled in Chrome DevTools. This setting keeps `document.visibilityState` set to `visible` and prevents `visibilitychange` events, which TanStack Query uses for its default focus handling.
110​
111Disable **Emulate a focused page** in the DevTools **Rendering** panel, then switch to another tab and return to test window focus refetching. See the [Chrome DevTools documentation](https://developer.chrome.com/docs/devtools/rendering/apply-effects#emulate_a_focused_page) for more details.