Skip to content

Instantly share code, notes, and snippets.

@tomorrowevening
Created January 3, 2024 20:40
Show Gist options
  • Save tomorrowevening/6f5af7c1edb0bfc3fedd995e9b8f27e9 to your computer and use it in GitHub Desktop.
Save tomorrowevening/6f5af7c1edb0bfc3fedd995e9b8f27e9 to your computer and use it in GitHub Desktop.
React hook to detect online/offline connection states
import { useEffect, useState } from "react";
export default 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;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment