UNPKG

qol-hooks

Version:

A collection of React hooks to improve the quality of life of developers.

38 lines (37 loc) 1.06 kB
import { useState, useEffect } from "react"; /** * Custom hook to track the online status of the user. * @returns {boolean} The online status of the user. * * @example```tsx * const Component = () => { * const isOnline = useOnlineStatus(); * * return ( * <div> * {isOnline ? "Online" : "Offline"} * </div> * )}; * ``` */ function useOnlineStatus() { const [isOnline, setIsOnline] = useState(navigator.onLine); useEffect(() => { /** * Event handler for the 'online' event. */ const handleOnline = () => setIsOnline(true); /** * Event handler for the 'offline' event. */ const handleOffline = () => setIsOnline(false); window.addEventListener("online", handleOnline); window.addEventListener("offline", handleOffline); return () => { window.removeEventListener("online", handleOnline); window.removeEventListener("offline", handleOffline); }; }, []); return isOnline; } export default useOnlineStatus;