Created
December 30, 2022 23:34
-
-
Save kivircik-parantez/8a3b2bcc8cc2472cd5878d3b147b64eb to your computer and use it in GitHub Desktop.
Subscribing to an external store
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
function subscribe(callback) { | |
window.addEventListener('online', callback); | |
window.addEventListener('offline', callback); | |
return () => { | |
window.removeEventListener('online', callback); | |
window.removeEventListener('offline', callback); | |
}; | |
} | |
function useOnlineStatus() { | |
// ✅ Good: Subscribing to an external store with a built-in Hook | |
return useSyncExternalStore( | |
subscribe, // React won't resubscribe for as long as you pass the same function | |
() => navigator.onLine, // How to get the value on the client | |
() => true // How to get the value on the server | |
); | |
} | |
function ChatIndicator() { | |
const isOnline = useOnlineStatus(); | |
// ... | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment