← articleshooks unleashed

useNetworkStatus: react to online/offline

A custom hook that listens to window online/offline events and returns a boolean.

Some features only make sense when the browser has a network connection. This hook exposes navigator.onLine and keeps it updated when connectivity changes.

The hook

// useNetworkStatus.js
import { useState, useEffect } from "react";

const useNetworkStatus = () => {
  const [status, setStatus] = useState(navigator.onLine);

  useEffect(() => {
    const setOnline = () => {
      setStatus(true);
    };

    const setOffline = () => {
      setStatus(false);
    };

    window.addEventListener("online", setOnline);
    window.addEventListener("offline", setOffline);

    return () => {
      window.removeEventListener("online", setOnline);
      window.removeEventListener("offline", setOffline);
    };
  }, []);

  return status;
};

export default useNetworkStatus;

How it works

Initial state comes from navigator.onLine. The effect registers online and offline listeners on window, updates state when either fires, and removes the listeners on unmount.

Example: show offline banner

import React from 'react';
import useNetworkStatus from './useNetworkStatus';

const RealTimeApp = () => {
  const isOnline = useNetworkStatus();

  return (
    <div className="real-time-app">
      <h1>Real-time app</h1>
      {!isOnline && <p>You are offline. Some features are unavailable.</p>}
      <p>Status: {isOnline ? 'Online' : 'Offline'}</p>
    </div>
  );
}

export default RealTimeApp;

Notes

  • navigator.onLine only tells you the browser thinks it has a route to the network. It can be true while requests still fail (captive portal, flaky Wi‑Fi).
  • For critical paths, still handle fetch errors and retry rather than trusting this hook alone.