Skip to main content

OnlineManager

Manages online/offline network state and notifies subscribers when the network state changes. This is used by TanStack Query to automatically pause and resume queries based on network availability.

Instance

A singleton instance is exported as onlineManager:

Methods

setEventListener

Sets up a custom event listener for online/offline events.
SetupFn
required
A function that sets up online/offline event listeners. The setup function receives a setOnline callback and should return a cleanup function.Type definition:
Parameters:
  • setOnline - Callback to notify the manager of network state changes. Call with true when online, false when offline.
Returns:
  • A cleanup function that will be called when the event listener is removed or replaced
Usage:
Default behavior: By default, the OnlineManager listens to online and offline events on the window:

setOnline

Manually sets the online state.
boolean
required
The new online state. true indicates the network is available, false indicates offline.
Usage:
Behavior:
  • Only notifies listeners if the online state has actually changed
  • All subscribed listeners are notified of the new state
  • This is automatically called by the event listener setup function

subscribe

Subscribes to online/offline state changes.
(online: boolean) => void
required
A callback function that will be called whenever the online state changes. The callback receives a boolean indicating whether the network is currently online.
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
  • Each listener is called with the current online state when it changes

isOnline

Returns the current online state.
Returns: true if the network is currently online, false otherwise. Usage:
Behavior:
  • Returns the current internal online state
  • Defaults to true (online) when the OnlineManager is first created
  • Can be manually updated via setOnline() or automatically via event listeners

Complete Example

Testing Example

Integration with TanStack Query

The OnlineManager is used internally by TanStack Query to implement network-aware query behavior:

Network Modes

TanStack Query uses the OnlineManager to support different network modes:
  • online - Queries/mutations pause when offline
  • always - Queries/mutations run regardless of online state
  • offlineFirst - Queries/mutations run, but failures are retried when back online

Platform Support

  • Browser: Uses online and offline events by default
  • React Native: Requires custom setup with NetInfo or similar
  • Node.js: Always returns true by default (no network detection)

Type Definitions

See Also