FocusManager
Manages window focus state and notifies subscribers when the focus state changes. This is used by TanStack Query to automatically refetch queries when the window regains focus.Instance
A singleton instance is exported asfocusManager:
Methods
setEventListener
Sets up a custom event listener for focus events.A function that sets up focus event listeners. The setup function receives a Parameters:
setFocused callback and should return a cleanup function.Type definition:setFocused- Callback to notify the manager of focus changes. Call withtruewhen focused,falsewhen blurred, or no arguments to trigger focus detection.
- A cleanup function that will be called when the event listener is removed or replaced
visibilitychange event on the window:
setFocused
Manually sets the focused state.The new focused state. If not provided, the
onFocus method will be called to notify listeners with the current focus state.- Only notifies listeners if the focused state has changed
- If called without arguments, triggers
onFocus()which notifies all listeners - Updates the internal focused state when a boolean is provided
subscribe
Subscribes to focus state changes.A callback function that will be called whenever the focus state changes. The callback receives a boolean indicating whether the window is currently focused.
- Automatically sets up the event listener on the first subscription
- Cleans up the event listener when the last subscriber unsubscribes
- Multiple listeners can be added simultaneously
isFocused
Returns the current focused state.true if the window is currently focused, false otherwise.
Usage:
- If a focused state has been explicitly set via
setFocused(), returns that value - Otherwise, checks if
document.visibilityState !== 'hidden' - Returns
trueby default if the document API is unavailable (e.g., React Native)
Complete Example
Integration with TanStack Query
The FocusManager is used internally by TanStack Query to implement automatic refetching when the window regains focus. You can configure this behavior using query options:Platform Support
- Browser: Uses
visibilitychangeevent by default - React Native: Requires custom setup with
AppState - Node.js: No default focus detection (always returns
true)
Type Definitions
See Also
- OnlineManager - Similar manager for online/offline state
- Window Focus Refetching