JAVASCRIPT
Detecting Network Status with `useNetworkStatus`
A custom React hook to detect and manage the current online or offline network status of the browser, useful for responsive UI and data syncing.
import { useState, useEffect } from 'react';
export const useNetworkStatus = () => {
const [isOnline, setIsOnline] = useState(navigator.onLine);
useEffect(() => {
const handleOnline = () => setIsOnline(true);
const handleOffline = () => setIsOnline(false);
window.addEventListener('online', handleOnline);
window.addEventListener('offline', handleOffline);
return () => {
window.removeEventListener('online', handleOnline);
window.removeEventListener('offline', handleOffline);
};
}, []);
return { isOnline };
};
How it works: The `useNetworkStatus` hook provides a simple way to track the browser's online/offline status. It initializes `isOnline` based on `navigator.onLine` and then uses `useEffect` to subscribe to 'online' and 'offline' events on the `window` object. This allows components to react dynamically to changes in network connectivity, displaying appropriate messages or adjusting data synchronization strategies.