JAVASCRIPT

Detect User Online Status with a `useOnlineStatus` Hook

Build a custom `useOnlineStatus` React hook to detect and respond to changes in the user's network connection, providing real-time feedback in your application.

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);

    return () => {
      window.removeEventListener('online', handleOnline);
      window.removeEventListener('offline', handleOffline);
    };
  }, []);

  return isOnline;
}

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

//   return (
//     <p>You are {isOnline ? 'online' : 'offline'}.</p>
//   );
// }
How it works: This `useOnlineStatus` hook determines if the user's browser is currently online or offline. It initializes its state with `navigator.onLine` and then uses `useEffect` to subscribe to the `online` and `offline` browser events. When these events fire, the state is updated accordingly. The cleanup function unsubscribes from the events to prevent 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