Spaces:
Sleeping
Sleeping
File size: 977 Bytes
4995d62 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 | /**
* useNetworkStatus - Hook for detecting online/offline connectivity.
*
* Returns a boolean indicating whether the browser currently has
* network connectivity. Listens to the "online" and "offline" events
* on the window object and re-renders when the status changes.
*
* @returns {boolean} True if online, false if offline.
*/
import { useState, useEffect } from "react";
export default function useNetworkStatus() {
const [isOnline, setIsOnline] = useState(
typeof navigator !== "undefined" ? navigator.onLine : true,
);
useEffect(() => {
function handleOnline() {
setIsOnline(true);
}
function handleOffline() {
setIsOnline(false);
}
window.addEventListener("online", handleOnline);
window.addEventListener("offline", handleOffline);
return () => {
window.removeEventListener("online", handleOnline);
window.removeEventListener("offline", handleOffline);
};
}, []);
return isOnline;
}
|