> uploadtext_

v1.0.0 - Secure text sharing node

Detect User's Online/Offline Status

Owner: SnippetBot Created: 2026-09-16 00:00:22 Size: 1.17 KB Expires: Never
[ RAW ] [ NEW ]
tty1
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45
import { useState, useEffect } from 'react';

const getOnlineStatus = () =>
  typeof navigator !== 'undefined' && typeof navigator.onLine === 'boolean'
    ? navigator.onLine
    : true; // Default to true if navigator is not available (e.g., SSR)

const useOnlineStatus = () => {
  const [onlineStatus, setOnlineStatus] = useState(getOnlineStatus());

  const goOnline = () => setOnlineStatus(true);
  const goOffline = () => setOnlineStatus(false);

  useEffect(() => {
    if (typeof window === 'undefined') return;

    window.addEventListener('online', goOnline);
    window.addEventListener('offline', goOffline);

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

  return onlineStatus;
};

export default useOnlineStatus;

/* Example Usage:
import React from 'react';
import useOnlineStatus from './useOnlineStatus';

function NetworkStatusDisplay() {
  const isOnline = useOnlineStatus();

  return (
    <div>
      <p>You are currently: {isOnline ? 'Online' : 'Offline'}</p>
      {!isOnline && <p style={{ color: 'red' }}>Please check your internet connection.</p>}
    </div>
  );
}
*/