Created
January 3, 2024 20:40
-
-
Save tomorrowevening/6f5af7c1edb0bfc3fedd995e9b8f27e9 to your computer and use it in GitHub Desktop.
React hook to detect online/offline connection states
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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