Yevhen Klymentiev
dark
light
console
darkness
y.klymentiev@gmail.com
Reusable Snippets|Practical utility code for everyday use — custom-built and ready to share

detectOnlineStatus

Detects network online/offline status changes and provides a listener.

TypeScript
Copied!
1/**
2 * Detects network online/offline status changes and provides a listener.
3 *
4 * @param callback - Function called with current online status (true/false) when it changes.
5 * @returns Unsubscribe function to stop listening.
6 *
7 * @example
8 * const unsubscribe = detectOnlineStatus(status => console.log('Online:', status));
9 * // Later
10 * unsubscribe();
11 */
12export function detectOnlineStatus(callback: (isOnline: boolean) => void): () => void {
13  const handler = () => callback(navigator.onLine);
14
15  window.addEventListener('online', handler);
16  window.addEventListener('offline', handler);
17
18  // Emit current status immediately
19  callback(navigator.onLine);
20
21  return () => {
22    window.removeEventListener('online', handler);
23    window.removeEventListener('offline', handler);
24  };
25}
  • Real-Time Detection

    Reacts immediately to browser online and offline events, allowing apps to respond dynamically to connectivity changes.

  • Immediate Initial Callback

    Invokes the callback right away with the current network status - no need to wait for the first event.

  • Unsubscribe Mechanism

    Returns a clean and safe teardown function, promoting memory safety and preventing listener leaks.

  • Simple, Declarative API

    Offers a lightweight, intuitive interface suitable for a wide range of applications without introducing dependencies.

Tests | Examples

TypeScript
Copied!
1beforeEach(() => {
2  // @ts-ignore
3  global.navigator.__defineGetter__('onLine', () => true);
4});
5
6test('calls callback immediately and on events', () => {
7  const cb = jest.fn();
8  const unsubscribe = detectOnlineStatus(cb);
9
10  expect(cb).toHaveBeenCalledWith(true);
11
12  // Simulate offline
13  // @ts-ignore
14  global.navigator.__defineGetter__('onLine', () => false);
15  window.dispatchEvent(new Event('offline'));
16
17  expect(cb).toHaveBeenCalledWith(false);
18
19  unsubscribe();
20
21  // Try triggering again to ensure unsubscribe works
22  window.dispatchEvent(new Event('online'));
23  expect(cb).toHaveBeenCalledTimes(2);
24});

Common Use Cases

  • Offline UI Indicators

    Show banners or disable functionality when the user goes offline.

  • Data Sync Logic

    Automatically resume pending sync operations when a connection is restored.

  • Progressive Web Apps (PWAs)

    Monitor connectivity to adapt user experience based on network availability.

  • User Notifications

    Alert users when they lose or regain connection, especially in collaborative or real-time apps.

  • Conditional API Requests

    Prevent fetches or retries when the device is known to be offline.

Codebase: Utilities -> Network -> detectOnlineStatus | Yevhen Klymentiev