Skip to main content

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 as focusManager:

Methods

setEventListener

Sets up a custom event listener for focus events.
SetupFn
required
A function that sets up focus event listeners. The setup function receives a setFocused callback and should return a cleanup function.Type definition:
Parameters:
  • setFocused - Callback to notify the manager of focus changes. Call with true when focused, false when blurred, or no arguments to trigger focus detection.
Returns:
  • A cleanup function that will be called when the event listener is removed or replaced
Usage:
Default behavior: By default, the FocusManager listens to the visibilitychange event on the window:

setFocused

Manually sets the focused state.
boolean
The new focused state. If not provided, the onFocus method will be called to notify listeners with the current focus state.
Usage:
Behavior:
  • 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.
(focused: boolean) => void
required
A callback function that will be called whenever the focus state changes. The callback receives a boolean indicating whether the window is currently focused.
Returns: An unsubscribe function that removes the listener when called. Usage:
Behavior:
  • 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.
Returns: true if the window is currently focused, false otherwise. Usage:
Behavior:
  • If a focused state has been explicitly set via setFocused(), returns that value
  • Otherwise, checks if document.visibilityState !== 'hidden'
  • Returns true by 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 visibilitychange event by default
  • React Native: Requires custom setup with AppState
  • Node.js: No default focus detection (always returns true)

Type Definitions

See Also