Skip to content

useNetwork ​

Hook to track network status

sensors
test coverage
Last changed: last month

TIP

This hook uses navigator.connection browser api to provide enhanced functionality. Make sure to check for compatibility with different browsers when using this api

Installation ​

Library
CLI
Manual
typescript
import { useNetwork } from '@siberiacancode/reactuse';

Usage ​

typescript
const { online, downlink, downlinkMax, effectiveType, rtt, saveData, type } = useNetwork();

Demo ​

Api ​

Returns

UseNetworkReturn

Type declaration ​

typescript
export interface Connection extends EventTarget {
  readonly downlink: number;
  readonly downlinkMax: number;
  readonly effectiveType: '2g' | '3g' | '4g' | 'slow-2g';
  readonly rtt: number;
  readonly saveData: boolean;
  onChange: (event: Event) => void;
  readonly type:
    | 'bluetooth'
    | 'cellular'
    | 'ethernet'
    | 'mixed'
    | 'none'
    | 'other'
    | 'unknown'
    | 'wifi'
    | 'wimax';
}

interface Navigator {
    readonly connection: Connection;
    readonly mozConnection: Connection;
    readonly webkitConnection: Connection;
  }

export type ConnectionType = Connection['type'];

export type ConnectionEffectiveType = Connection['effectiveType'];

export interface UseNetworkReturn {
  /** The estimated downlink speed in megabits per seconds */
  downlink?: Connection['downlink'];
  /** The maximum downlink speed, if available */
  downlinkMax?: Connection['downlinkMax'];
  /** The effective type of connection (e.g., '2g', '3g', '4g') */
  effectiveType?: Connection['effectiveType'];
  /** Indicates if the device is currently online */
  online: boolean;
  /** The estimated round-trip time in milliseconds */
  rtt?: Connection['rtt'];
  /** Indicates if the user has enabled data saving mode */
  saveData?: Connection['saveData'];
  /** The type of network connection (e.g., 'wifi', 'cellular') */
  type?: Connection['type'];
}

Source ​

Source • Demo

Contributors ​

D
debabin
debabin
H
hywax
hywax
W
waldymarxthf
waldymarxthf

Released under the MIT License.