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

focusManager.md

76 lines1.8 KB

1---
2id: FocusManager
3title: FocusManager
4---
5​
6The `FocusManager` manages the focus state within TanStack Query.
7​
8It can be used to change the default event listeners or to manually change the focus state.
9​
10Its available methods are:
11​
12- [`setEventListener`](#focusmanagerseteventlistener)
13- [`subscribe`](#focusmanagersubscribe)
14- [`setFocused`](#focusmanagersetfocused)
15- [`isFocused`](#focusmanagerisfocused)
16​
17## `focusManager.setEventListener`
18​
19`setEventListener` can be used to set a custom event listener:
20​
21```tsx
22import { focusManager } from '@tanstack/react-query'
23​
24focusManager.setEventListener((handleFocus) => {
25 // Listen to visibilitychange
26 if (typeof window !== 'undefined' && window.addEventListener) {
27 window.addEventListener('visibilitychange', handleFocus, false)
28 }
29​
30 return () => {
31 // Be sure to unsubscribe if a new handler is set
32 window.removeEventListener('visibilitychange', handleFocus)
33 }
34})
35```
36​
37## `focusManager.subscribe`
38​
39`subscribe` can be used to subscribe to changes in the visibility state. It returns an unsubscribe function:
40​
41```tsx
42import { focusManager } from '@tanstack/react-query'
43​
44const unsubscribe = focusManager.subscribe((isVisible) => {
45 console.log('isVisible', isVisible)
46})
47```
48​
49## `focusManager.setFocused`
50​
51`setFocused` can be used to manually set the focus state. Set `undefined` to fall back to the default focus check.
52​
53```tsx
54import { focusManager } from '@tanstack/react-query'
55​
56// Set focused
57focusManager.setFocused(true)
58​
59// Set unfocused
60focusManager.setFocused(false)
61​
62// Fallback to the default focus check
63focusManager.setFocused(undefined)
64```
65​
66**Options**
67​
68- `focused: boolean | undefined`
69​
70## `focusManager.isFocused`
71​
72`isFocused` can be used to get the current focus state.
73​
74```tsx
75const isFocused = focusManager.isFocused()
76```