@storm-stack/hooks
Version:
A collection of React hooks used by Storm Software in various client libraries and applications.
54 lines (53 loc) • 1.74 kB
JavaScript
import { isEqual } from "@storm-stack/types/type-checks/is-equal";
import { useRef, useSyncExternalStore } from "react";
const getConnection = () => {
const connectionKey = "connection";
const mozConnectionKey = "mozConnection";
const webkitConnectionKey = "webkitConnection";
return navigator[connectionKey] || navigator[mozConnectionKey] || navigator[webkitConnectionKey];
};
export const useNetworkStateSubscribe = (callback) => {
window.addEventListener("online", callback, { passive: true });
window.addEventListener("offline", callback, { passive: true });
const connection = getConnection();
if (connection) {
connection.addEventListener("change", callback, { passive: true });
}
return () => {
window.removeEventListener("online", callback);
window.removeEventListener("offline", callback);
if (connection) {
connection.removeEventListener("change", callback);
}
};
};
const getNetworkStateServerSnapshot = () => {
throw Error("useNetworkState is a client-only hook");
};
export function useNetworkState() {
const cache = useRef({});
const getSnapshot = () => {
const online = navigator.onLine;
const connection = getConnection();
const nextState = {
online,
downlink: connection?.downlink,
downlinkMax: connection?.downlinkMax,
effectiveType: connection?.effectiveType,
rtt: connection?.rtt,
saveData: connection?.saveData,
type: connection?.type
};
if (isEqual(cache.current, nextState)) {
return cache.current;
} else {
cache.current = nextState;
return nextState;
}
};
return useSyncExternalStore(
useNetworkStateSubscribe,
getSnapshot,
getNetworkStateServerSnapshot
);
}