JAVASCRIPT

Detect Online/Offline Status with a Custom Hook

Create a simple custom React hook to track the user's network connection status (online or offline), enabling responsive UI/UX based on connectivity.

import { useState, useEffect } from 'react';

function useOnlineStatus() {
  const [isOnline, setIsOnline] = useState(navigator.onLine);

  useEffect(() => {
    const handleOnline = () => setIsOnline(true);
    const handleOffline = () => setIsOnline(false);

    window.addEventListener('online', handleOnline);
    window.addEventListener('offline', handleOffline);

    // Cleanup event listeners on component unmount
    return () => {
      window.removeEventListener('online', handleOnline);
      window.removeEventListener('offline', handleOffline);
    };
  }, []); // Empty dependency array ensures effect runs once on mount

  return isOnline;

  // Example Usage:
  /*
  function NetworkStatusIndicator() {
    const isOnline = useOnlineStatus();

    return (
      <p>You are currently: <strong>{isOnline ? 'Online' : 'Offline'}</strong></p>
    );
  }
  */
}
How it works: This `useOnlineStatus` hook provides a simple way to determine the user's current network connectivity status. It initializes its state based on `navigator.onLine` and then listens for `online` and `offline` events on the `window` object. The hook automatically updates and returns `true` if the user is online, and `false` if they are offline, allowing you to build network-aware React components.

Need help integrating this into your project?

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

Hire DigitalCodeLabs