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 asonlineManager:
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 Parameters:
setOnline callback and should return a cleanup function.Type definition:setOnline- Callback to notify the manager of network state changes. Call withtruewhen online,falsewhen offline.
- A cleanup function that will be called when the event listener is removed or replaced
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.- 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.
- 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.true if the network is currently online, false otherwise.
Usage:
- 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 offlinealways- Queries/mutations run regardless of online stateofflineFirst- Queries/mutations run, but failures are retried when back online
Platform Support
- Browser: Uses
onlineandofflineevents by default - React Native: Requires custom setup with
NetInfoor similar - Node.js: Always returns
trueby default (no network detection)
Type Definitions
See Also
- FocusManager - Similar manager for window focus state
- Network Mode