Skip to main content
The focusManager is a singleton that manages window focus state and notifies subscribers when the focus state changes. It listens to the visibilitychange event by default and can be customized with custom event listeners.

Import

Methods

subscribe

Subscribe to focus state changes.
(focused: boolean) => void
required
Callback function that will be called when the focus state changes. Receives a boolean indicating whether the window is focused.
() => void
Returns an unsubscribe function that removes the listener when called.

Example

setEventListener

Set a custom event listener for focus changes. This allows you to customize how focus is detected.
SetupFn
required
A setup function that receives a setFocused callback and returns an optional cleanup function.Type signature:
The setup function should call setFocused(true) when the window gains focus and setFocused(false) when it loses focus. If called with no arguments, it will use the default focus detection.

Example

setFocused

Manually set the focus state.
boolean
The new focus state. If not provided, the focus state will be determined automatically using the default detection method.

Example

isFocused

Get the current focus state.
boolean
Returns true if the window is focused, false otherwise. If no manual focus state has been set, it checks document.visibilityState !== 'hidden'.

Example

Default Behavior

By default, the focusManager listens to the browser’s visibilitychange event to detect when the window gains or loses focus. This works in most browser environments. In environments where window.addEventListener is not available (like React Native), you need to set up a custom event listener using setEventListener.

Use Cases

Custom Focus Detection

You can provide custom focus detection logic for different environments:

Disable Automatic Focus Refetching

You can prevent automatic refetching on window focus:

Testing

In tests, you can control focus state manually: