@uiw/react-use-online
Version:
useOnline is a tiny, zero-dependency hook for responding to online/offline changes.
18 lines • 508 B
JavaScript
import { useSyncExternalStore } from 'react';
function getSnapshot() {
return navigator.onLine;
}
function getServerSnapshot() {
return true;
}
function subscribe(callback) {
window.addEventListener('online', callback);
window.addEventListener('offline', callback);
return () => {
window.removeEventListener('online', callback);
window.removeEventListener('offline', callback);
};
}
export function useOnline() {
return useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot);
}