JAVASCRIPT
Track Browser Online/Offline Status with useOnlineStatus
Implement a useOnlineStatus React hook to monitor network connectivity, allowing components to display different UI based on online/offline state.
import { useState, useEffect } from 'react';
const getOnlineStatus = () =>
typeof navigator !== 'undefined' && typeof navigator.onLine === 'boolean'
? navigator.onLine
: true;
const useOnlineStatus = () => {
const [onlineStatus, setOnlineStatus] = useState(getOnlineStatus());
const goOnline = () => setOnlineStatus(true);
const goOffline = () => setOnlineStatus(false);
useEffect(() => {
window.addEventListener('online', goOnline);
window.addEventListener('offline', goOffline);
return () => {
window.removeEventListener('online', goOnline);
window.removeEventListener('offline', goOffline);
};
}, []);
return onlineStatus;
};
export default useOnlineStatus;
How it works: The `useOnlineStatus` hook allows your React components to dynamically respond to changes in the browser's network connectivity. It leverages the `navigator.onLine` property and 'online'/'offline' browser events. The hook initializes its state with the current online status. It then registers event listeners for 'online' and 'offline' events on the `window` object to update the state accordingly. The `useEffect` cleanup function ensures these event listeners are removed when the component unmounts, maintaining good resource management. The hook returns a boolean indicating whether the user is currently online.