← Back to all snippets
JAVASCRIPT

Custom useNetworkStatus Hook for Online/Offline Detection

A React custom hook to efficiently track and react to changes in the user's network connection status (online or offline), enhancing UI responsiveness.

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;

// How to use:
// import useNetworkStatus from './useNetworkStatus';
// function MyComponent() {
//   const isOnline = useNetworkStatus();
//   return (
//     <div>
//       <p>You are {isOnline ? 'online' : 'offline'}</p>
//     </div>
//   );
// }
How it works: This custom hook leverages React's `useState` and `useEffect` to monitor the browser's network status. It initializes its state based on `navigator.onLine` and then adds event listeners for the 'online' and 'offline' window events. When the network status changes, the state is updated, causing any consuming component to re-render with the latest status. The `useEffect` cleanup function ensures that event listeners are properly removed when the component unmounts.

Need help integrating this into your project?

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

Hire DigitalCodeLabs