typescriptbeginner

useOnlineStatus Hook

Tracks browser online/offline status and re-renders when connectivity changes.

typescript
import { useSyncExternalStore } from 'react';

function subscribe(callback: () => void) {
  window.addEventListener('online', callback);
  window.addEventListener('offline', callback);
  return () => {
    window.removeEventListener('online', callback);
    window.removeEventListener('offline', callback);
  };
}

export function useOnlineStatus(): boolean {
  return useSyncExternalStore(
    subscribe,
    () => navigator.onLine,
    () => true // SSR fallback
  );
}

Use Cases

  • Offline-first apps
  • Connection status indicators

Tags

Related Snippets

Similar patterns you can reuse in the same workflow.