Skip to content

Instantly share code, notes, and snippets.

@kivircik-parantez
Created December 30, 2022 23:34
Show Gist options
  • Save kivircik-parantez/8a3b2bcc8cc2472cd5878d3b147b64eb to your computer and use it in GitHub Desktop.
Save kivircik-parantez/8a3b2bcc8cc2472cd5878d3b147b64eb to your computer and use it in GitHub Desktop.
Subscribing to an external store
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