Skip to content

hook offlinemode

Paulo Gomes da Cruz Junior edited this page Nov 19, 2025 · 1 revision

📡 useOfflineMode Hook

Overview

useOfflineMode is a custom React hook that provides real-time awareness of the application's online/offline status, along with direct access to subscribe/unsubscribe methods for advanced use cases. It leverages a shared store to track connectivity, allowing components to reactively update their UI or logic based on whether the user is online or offline, or to subscribe to status changes programmatically.

This hook is especially useful for Progressive Web Apps (PWAs) or any application that needs to gracefully handle network interruptions, offline caching, or background synchronization.

🧪 Usage Example

import useOfflineMode from '@/hooks/useOfflineMode';

function StatusBanner() {
  const { isOnline } = useOfflineMode();

  return (
    <div>
      {isOnline ? 'You are online!' : 'You are offline. Some features may be unavailable.'}
    </div>
  );
}

// Advanced: subscribing to online status changes manually
import { useEffect } from 'react';

function CustomListenerComponent() {
  const { subscribe, unsubscribe } = useOfflineMode();

  useEffect(() => {
    const listener = (online) => {
      // handle status change
    };
    subscribe(listener);
    return () => unsubscribe(listener);
  }, [subscribe, unsubscribe]);
  // ...
}

🔍 Implementation Details

  • Store-backed: Uses a shared onlineStatusStore to listen for browser online/offline events and manage subscriptions.
  • Direct Subscription: Exposes subscribe and unsubscribe methods for advanced manual control over online status listeners.
  • Feature Flag: Respects a feature flag (VITE_FEATURES_OFFLINE) to enable/disable offline support. If disabled, the app always reports as online.
  • SSR Safe: Designed to work in server-side rendering environments by defaulting to online if the browser API is unavailable.
  • Cleanup: Automatically unsubscribes from the store on component unmount to prevent memory leaks when using the hook's state.

📦 Return Type

function useOfflineMode(): {
  isOnline: boolean;
  subscribe: (listener: (online: boolean) => void) => () => void;
  unsubscribe: (listener: (online: boolean) => void) => void;
};
  • isOnline: true if the app is online, false if offline.
  • subscribe: Function to subscribe to online status changes. Returns an unsubscribe function.
  • unsubscribe: Function to manually remove a listener.

💡 Why It Matters

Handling offline scenarios is critical for modern web apps, especially PWAs. useOfflineMode makes it easy to:

  • Show offline banners or notifications
  • Disable or queue actions that require connectivity
  • Subscribe to online status changes for custom logic
  • Provide a seamless user experience regardless of network status

For more hooks and context utilities, see the contexts-and-hooks documentation.

Clone this wiki locally