Created
July 8, 2021 09:49
-
-
Save tjinlag/8347778499500d06a0a487ad79f55437 to your computer and use it in GitHub Desktop.
React Custom Hook: get network status - online or offline
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 { useState, useEffect } from "react"; | |
const useOnlineStatus = () => { | |
const [online, setOnline] = useState(true); | |
useEffect(() => { | |
const goOnline = () => setOnline(true); | |
const goOffline = () => setOnline(false); | |
window.addEventListener('online', goOnline); | |
window.addEventListener('offline', goOffline); | |
return () => { | |
window.removeEventListener('online', goOnline); | |
window.removeEventListener('offline', goOffline); | |
}; | |
}, []); | |
return online; | |
}; | |
export default useOnlineStatus; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment