1import { useEffect, useState } from "react";
2
3interface NetworkState {
4 online: boolean;
5 since?: Date;
6 downlink?: number;
7 downlinkMax?: number;
8 effectiveType?: string;
9 rtt?: number;
10 saveData?: boolean;
11 type?: string;
12}
13
14export function useNetworkState(): NetworkState {
15 const [state, setState] = useState<NetworkState>({
16 online: typeof navigator !== "undefined" ? navigator.onLine : true,
17 });
18
19 useEffect(() => {
20 const handleOnline = () => {
21 setState((prevState) => ({
22 ...prevState,
23 online: true,
24 since: new Date(),
25 }));
26 };
27
28 const handleOffline = () => {
29 setState((prevState) => ({
30 ...prevState,
31 online: false,
32 since: new Date(),
33 }));
34 };
35
36 const handleConnectionChange = () => {
37 const connection = (navigator as any).connection;
38 if (connection) {
39 setState((prevState) => ({
40 ...prevState,
41 downlink: connection.downlink,
42 downlinkMax: connection.downlinkMax,
43 effectiveType: connection.effectiveType,
44 rtt: connection.rtt,
45 saveData: connection.saveData,
46 type: connection.type,
47 }));
48 }
49 };
50
51 window.addEventListener("online", handleOnline);
52 window.addEventListener("offline", handleOffline);
53
54 const connection = (navigator as any).connection;
55 if (connection) {
56 connection.addEventListener("change", handleConnectionChange);
57 handleConnectionChange();
58 }
59
60 return () => {
61 window.removeEventListener("online", handleOnline);
62 window.removeEventListener("offline", handleOffline);
63 if (connection) {
64 connection.removeEventListener("change", handleConnectionChange);
65 }
66 };
67 }, []);
68
69 return state;
70}