The FocusManager
manages the focus state within TanStack Query.
It can be used to change the default event listeners or to manually change the focus state.
Its available methods are:
focusManager.setEventListener
#
setEventListener
can be used to set a custom event listener:
1import { focusManager } from '@tanstack/react-query'
2
3focusManager.setEventListener((handleFocus) => {
4 // Listen to visibilitychange
5 if (typeof window !== 'undefined' && window.addEventListener) {
6 window.addEventListener('visibilitychange', handleFocus, false)
7 }
8
9 return () => {
10 // Be sure to unsubscribe if a new handler is set
11 window.removeEventListener('visibilitychange', handleFocus)
12 }
13})
focusManager.subscribe
#
subscribe
can be used to subscribe to changes in the visibility state. It returns an unsubscribe function:
1import { focusManager } from '@tanstack/react-query'
2
3const unsubscribe = focusManager.subscribe((isVisible) => {
4 console.log('isVisible', isVisible)
5})
focusManager.setFocused
#
setFocused
can be used to manually set the focus state. Set undefined
to fall back to the default focus check.
1import { focusManager } from '@tanstack/react-query'
2
3// Set focused
4focusManager.setFocused(true)
5
6// Set unfocused
7focusManager.setFocused(false)
8
9// Fallback to the default focus check
10focusManager.setFocused(undefined)
Options
focused: boolean | undefined
focusManager.isFocused
#
isFocused
can be used to get the current focus state.
1const isFocused = focusManager.isFocused()