JAVASCRIPT

Detect Browser Online/Offline Status

A React hook to efficiently track and provide the current browser's online or offline connectivity status, enabling network-aware user interfaces.

import { useState, useEffect } from 'react';

const getOnlineStatus = () =>
  typeof navigator !== 'undefined' && typeof navigator.onLine === 'boolean'
    ? navigator.onLine
    : true; // Default to online if navigator or onLine property is not available

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: This hook provides the current online/offline status of the browser. It initializes the state using `navigator.onLine`. A `useEffect` then attaches `online` and `offline` event listeners to the `window` object, updating the `onlineStatus` state whenever the network connectivity changes. The event listeners are properly removed during component unmount to prevent memory leaks. This is useful for building network-resilient UIs.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs