UNPKG

@wojtekmaj/react-hooks

Version:

A collection of React Hooks.

21 lines (20 loc) 716 B
import { useCallback, useState } from 'react'; import useEventListener from './useEventListener.js'; const isBrowser = typeof window !== 'undefined'; /** * Returns the online status of the browser. * * @returns {boolean | null} Online status of the browser */ export default function useOnLine() { const [onLine, setOnLine] = useState(isBrowser ? navigator.onLine : null); const handleOnline = useCallback(() => { setOnLine(true); }, []); const handleOffline = useCallback(() => { setOnLine(false); }, []); useEventListener(isBrowser ? window : null, 'online', handleOnline); useEventListener(isBrowser ? window : null, 'offline', handleOffline); return onLine; }