Skip to content

Commit 9c6865d

Browse files
committed
Refactor useNetworkState
1 parent 6eba0d6 commit 9c6865d

File tree

1 file changed

+24
-20
lines changed

1 file changed

+24
-20
lines changed

index.js

Lines changed: 24 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -839,28 +839,32 @@ const getConnection = () => {
839839
);
840840
};
841841

842-
export function useNetworkState() {
843-
const cache = React.useRef({});
842+
const useNetworkStateSubscribe = (callback) => {
843+
window.addEventListener("online", callback, { passive: true });
844+
window.addEventListener("offline", callback, { passive: true });
844845

845-
const subscribe = React.useCallback((callback) => {
846-
window.addEventListener("online", callback, { passive: true });
847-
window.addEventListener("offline", callback, { passive: true });
846+
const connection = getConnection();
848847

849-
const connection = getConnection();
848+
if (connection) {
849+
connection.addEventListener("change", callback, { passive: true });
850+
}
851+
852+
return () => {
853+
window.removeEventListener("online", callback);
854+
window.removeEventListener("offline", callback);
850855

851856
if (connection) {
852-
connection.addEventListener("change", callback, { passive: true });
857+
connection.removeEventListener("change", callback);
853858
}
859+
};
860+
};
854861

855-
return () => {
856-
window.removeEventListener("online", callback);
857-
window.removeEventListener("offline", callback);
862+
const getNetworkStateServerSnapshot = () => {
863+
throw Error("useNetworkState is a client-only hook");
864+
};
858865

859-
if (connection) {
860-
connection.removeEventListener("change", callback);
861-
}
862-
};
863-
}, []);
866+
export function useNetworkState() {
867+
const cache = React.useRef({});
864868

865869
const getSnapshot = () => {
866870
const online = navigator.onLine;
@@ -884,11 +888,11 @@ export function useNetworkState() {
884888
}
885889
};
886890

887-
const getServerSnapshot = () => {
888-
throw Error("useNetworkState is a client-only hook");
889-
};
890-
891-
return React.useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot);
891+
return React.useSyncExternalStore(
892+
useNetworkStateSubscribe,
893+
getSnapshot,
894+
getNetworkStateServerSnapshot
895+
);
892896
}
893897

894898
export function useObjectState(initialValue) {

0 commit comments

Comments
 (0)