JAVASCRIPT

Detect Online/Offline Network Status with a Custom React Hook

Create a custom React hook to efficiently detect and provide the current online or offline status of the user's browser, enabling adaptive UI experiences.

import { useState, useEffect } from 'react';

const useNetworkStatus = () => {
  const [isOnline, setIsOnline] = useState(navigator.onLine);

  useEffect(() => {
    const handleOnline = () => setIsOnline(true);
    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 useNetworkStatus;

// Example Usage:
/*
function NetworkStatusDisplay() {
  const isOnline = useNetworkStatus();

  return (
    <div>
      <p>Network Status: {isOnline ? 'Online' : 'Offline'}</p>
      {!isOnline && <p style={{ color: 'red' }}>You are currently offline.</p>}
    </div>
  );
}
*/
How it works: This custom `useNetworkStatus` hook leverages `useState` to manage the online state and `useEffect` to subscribe to `window`'s `online` and `offline` events. It initializes the state based on `navigator.onLine` and updates it whenever the network status changes, providing a real-time boolean `isOnline` flag. The `useEffect` cleanup function ensures event listeners are removed when the component unmounts, preventing memory leaks.

Need help integrating this into your project?

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

Hire DigitalCodeLabs