Skip to content

Instantly share code, notes, and snippets.

@charltoons
Created December 17, 2024 19:32
Show Gist options
  • Save charltoons/71a40f1c7b4d32be1c6edca9249a0233 to your computer and use it in GitHub Desktop.
Save charltoons/71a40f1c7b4d32be1c6edca9249a0233 to your computer and use it in GitHub Desktop.
Network status event handler using useSyncExternalStore
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