-
Notifications
You must be signed in to change notification settings - Fork 0
hook offlinemode
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.
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]);
// ...
}-
Store-backed: Uses a shared
onlineStatusStoreto listen for browser online/offline events and manage subscriptions. -
Direct Subscription: Exposes
subscribeandunsubscribemethods 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.
function useOfflineMode(): {
isOnline: boolean;
subscribe: (listener: (online: boolean) => void) => () => void;
unsubscribe: (listener: (online: boolean) => void) => void;
};-
isOnline:
trueif the app is online,falseif offline. - subscribe: Function to subscribe to online status changes. Returns an unsubscribe function.
- unsubscribe: Function to manually remove a listener.
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.