JAVASCRIPT

React `useNetworkStatus` Hook for Online/Offline Detection

Build a custom React `useNetworkStatus` hook to track and react to the user's online or offline network connectivity, useful for displaying warnings or adjusting application behavior.

import { useState, useEffect } from 'react';

function 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);
    };
  }, []); // Empty dependency array means this effect runs once on mount and cleans up on unmount

  return isOnline;
}

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

//   return (
//     <div>
//       <p>You are {isOnline ? 'online' : 'offline'}.</p>
//       {!isOnline && <div style={{ color: 'red' }}>Please check your internet connection!</div>}
//     </div>
//   );
// }
How it works: This `useNetworkStatus` hook detects and provides the current online/offline status of the user's browser. It subscribes to the browser's `online` and `offline` events, updating its internal state and returning a boolean value. This allows developers to display connectivity warnings or adapt application features based on network availability.

Need help integrating this into your project?

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

Hire DigitalCodeLabs