useNetworkState

Track the network connection status.

https://www.shaktools.com/shak-hooks
Network

API Reference

Installation

terminal
pnpm add @shak-hooks/usehooks
import.ts
import { useNetworkState } from "@shak-hooks/usehooks";
Source: packages/react/src/useNetworkState.ts

Signature

signature.ts
export function useNetworkState(): NetworkState

Parameters

No parameters.

Returns

NetworkState

Exported Types

types.ts
1export interface NetworkState {
2 online: boolean;
3 downlink?: number;
4 downlinkMax?: number;
5 effectiveType?: string;
6 rtt?: number;
7 saveData?: boolean;
8 type?: string;
9}

Implementation

use-network-state.ts
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}

Advertisement

Google Ads

Usage

example.tsx
1import { useNetworkState } from "@shak-hooks/usehooks";
2
3const result = useNetworkState();
4// result: NetworkState
5// Use values directly (React state).

Let‘s do great work together

Empowering creators with free, high-performance AI, SEO, and developer tools. Join thousands of users optimizing their workflow with Shak-Tools.

Tools10+ Free
UsersGlobal

Stay in the loop

Join our newsletter for the latest AI tools and updates.

ShakTools
© 2025 Shaktools. All Rights Reserved.Privacy Policy