Created
December 17, 2024 19:32
-
-
Save charltoons/71a40f1c7b4d32be1c6edca9249a0233 to your computer and use it in GitHub Desktop.
Network status event handler using useSyncExternalStore
This file contains hidden or 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
export function useOnlineStatusChange( | |
onOnline: () => void, | |
onOffline: () => void | |
) { | |
return useSyncExternalStore( | |
(callback) => { | |
window.addEventListener('online', onOnline); | |
window.addEventListener('online', callback); | |
window.addEventListener('offline', onOffline); | |
window.addEventListener('offline', callback); | |
return () => { | |
window.removeEventListener('online', onOnline); | |
window.removeEventListener('online', callback); | |
window.removeEventListener('offline', onOffline); | |
window.removeEventListener('offline', callback); | |
}; | |
}, | |
() => navigator.onLine, | |
() => true | |
); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment