useHooks.iov4.1.2
DocsBlogGitHub
Hooks
No hooks found in any category.

useNetworkInformation

sensors

Installation

npx usehooks-cli@latest add use-network-information

Description

A React hook that provides access to network connection information using the Network Information API. It tracks connection details like speed, type, and online status with real-time updates.

Return Type

UseNetworkInformationReturn
PropertyTypeDescription
networkInfoNetworkInformation | nullCurrent network connection information including downlink, effectiveType, rtt, saveData, and type
isOnlinebooleanWhether the browser is currently online
isSupportedbooleanWhether the Network Information API is supported in the current browser
refresh() => voidFunction to manually refresh the network information

Examples

Basic Network Status

Display current network connection information

1import { useNetworkInformation } from '@usehooks.io/use-network-information'; 2 3function NetworkStatus() { 4 const { networkInfo, isOnline, isSupported, refresh } = useNetworkInformation(); 5 6 if (!isSupported) { 7 return <div>Network Information API not supported</div>; 8 } 9 10 return ( 11 <div> 12 <h3>Network Status</h3> 13 <p>Online: {isOnline ? 'Yes' : 'No'}</p> 14 15 {networkInfo && ( 16 <div> 17 <p>Connection Type: {networkInfo.type || 'Unknown'}</p> 18 <p>Effective Type: {networkInfo.effectiveType || 'Unknown'}</p> 19 <p>Downlink: {networkInfo.downlink ? `${networkInfo.downlink} Mbps` : 'Unknown'}</p> 20 <p>RTT: {networkInfo.rtt ? `${networkInfo.rtt} ms` : 'Unknown'}</p> 21 <p>Save Data: {networkInfo.saveData ? 'Enabled' : 'Disabled'}</p> 22 </div> 23 )} 24 25 <button onClick={refresh}>Refresh Network Info</button> 26 </div> 27 ); 28}

Adaptive Content Loading

Adjust content quality based on connection speed

1import { useNetworkInformation } from '@usehooks.io/use-network-information'; 2import { useState, useEffect } from 'react'; 3 4function AdaptiveContent() { 5 const { networkInfo, isOnline } = useNetworkInformation(); 6 const [imageQuality, setImageQuality] = useState('high'); 7 8 useEffect(() => { 9 if (!networkInfo) return; 10 11 // Adjust quality based on effective connection type 12 switch (networkInfo.effectiveType) { 13 case 'slow-2g': 14 case '2g': 15 setImageQuality('low'); 16 break; 17 case '3g': 18 setImageQuality('medium'); 19 break; 20 case '4g': 21 default: 22 setImageQuality('high'); 23 break; 24 } 25 }, [networkInfo]); 26 27 if (!isOnline) { 28 return <div>You are offline. Please check your connection.</div>; 29 } 30 31 return ( 32 <div> 33 <h3>Adaptive Image Gallery</h3> 34 <p>Loading {imageQuality} quality images</p> 35 <p>Connection: {networkInfo?.effectiveType || 'Unknown'}</p> 36 37 <div className="image-gallery"> 38 <img 39 src={`/api/image?quality=${imageQuality}`} 40 alt="Adaptive content" 41 loading="lazy" 42 /> 43 {/* More adaptive content */} 44 </div> 45 </div> 46 ); 47}

Data Saver Mode

Respect user's data saving preferences

1import { useNetworkInformation } from '@usehooks.io/use-network-information'; 2import { useState } from 'react'; 3 4function DataSaverContent() { 5 const { networkInfo, isSupported } = useNetworkInformation(); 6 const [showFullContent, setShowFullContent] = useState(false); 7 8 const isDataSaverEnabled = networkInfo?.saveData; 9 const isSlowConnection = ['slow-2g', '2g'].includes(networkInfo?.effectiveType || ''); 10 11 const shouldLimitContent = isDataSaverEnabled || isSlowConnection; 12 13 if (!isSupported) { 14 return <div>Loading full content...</div>; 15 } 16 17 return ( 18 <div> 19 <h3>Article Content</h3> 20 21 {isDataSaverEnabled && ( 22 <div className="data-saver-notice"> 23 📱 Data Saver mode detected - showing optimized content 24 </div> 25 )} 26 27 {isSlowConnection && ( 28 <div className="slow-connection-notice"> 29 🐌 Slow connection detected - content optimized for speed 30 </div> 31 )} 32 33 <div className="article-preview"> 34 <p>Article preview content...</p> 35 </div> 36 37 {shouldLimitContent && !showFullContent ? ( 38 <button onClick={() => setShowFullContent(true)}> 39 Load Full Content 40 </button> 41 ) : ( 42 <div className="full-content"> 43 <p>Full article content with images and videos...</p> 44 <video controls={!isDataSaverEnabled}> 45 <source src="/video.mp4" type="video/mp4" /> 46 </video> 47 </div> 48 )} 49 </div> 50 ); 51}

Dependencies

react

Notes

  • The Network Information API is experimental and may not be supported in all browsers
  • Automatically listens for online/offline events and connection changes
  • Returns null for networkInfo when the API is not supported
  • Cleans up event listeners on component unmount
  • HTTPS required in production environments for security
  • Effective connection types: 'slow-2g', '2g', '3g', '4g'
  • Connection types include: 'bluetooth', 'cellular', 'ethernet', 'none', 'wifi', 'wimax', 'other', 'unknown'

Implementation

1'use client'; 2 3import { useState, useEffect, useCallback } from "react"; 4 5interface NetworkInformation { 6 downlink?: number; 7 downlinkMax?: number; 8 effectiveType?: "2g" | "3g" | "4g" | "slow-2g"; 9 rtt?: number; 10 saveData?: boolean; 11 type?: 12 | "bluetooth" 13 | "cellular" 14 | "ethernet" 15 | "none" 16 | "wifi" 17 | "wimax" 18 | "other" 19 | "unknown"; 20} 21 22interface UseNetworkInformationReturn { 23 networkInfo: NetworkInformation | null; 24 isOnline: boolean; 25 isSupported: boolean; 26 refresh: () => void; 27} 28 29export const useNetworkInformation = (): UseNetworkInformationReturn => { 30 const [networkInfo, setNetworkInfo] = useState<NetworkInformation | null>( 31 null 32 ); 33 const [isOnline, setIsOnline] = useState<boolean>( 34 typeof navigator !== "undefined" ? navigator.onLine : true 35 ); 36 37 const isSupported = 38 typeof navigator !== "undefined" && 39 "connection" in navigator && 40 navigator.connection !== undefined; 41 42 const updateNetworkInfo = useCallback(() => { 43 if (!isSupported) return; 44 45 const connection = (navigator as any).connection; 46 47 setNetworkInfo({ 48 downlink: connection.downlink, 49 downlinkMax: connection.downlinkMax, 50 effectiveType: connection.effectiveType, 51 rtt: connection.rtt, 52 saveData: connection.saveData, 53 type: connection.type, 54 }); 55 }, [isSupported]); 56 57 const handleOnlineStatusChange = useCallback(() => { 58 setIsOnline(navigator.onLine); 59 }, []); 60 61 const handleConnectionChange = useCallback(() => { 62 updateNetworkInfo(); 63 }, [updateNetworkInfo]); 64 65 useEffect(() => { 66 if (typeof window === "undefined") return; 67 68 // Initial network info 69 updateNetworkInfo(); 70 71 // Listen for online/offline events 72 window.addEventListener("online", handleOnlineStatusChange); 73 window.addEventListener("offline", handleOnlineStatusChange); 74 75 // Listen for connection changes 76 if (isSupported) { 77 const connection = (navigator as any).connection; 78 connection.addEventListener("change", handleConnectionChange); 79 } 80 81 return () => { 82 window.removeEventListener("online", handleOnlineStatusChange); 83 window.removeEventListener("offline", handleOnlineStatusChange); 84 85 if (isSupported) { 86 const connection = (navigator as any).connection; 87 connection.removeEventListener("change", handleConnectionChange); 88 } 89 }; 90 }, [ 91 isSupported, 92 updateNetworkInfo, 93 handleOnlineStatusChange, 94 handleConnectionChange, 95 ]); 96 97 return { 98 networkInfo, 99 isOnline, 100 isSupported, 101 refresh: updateNetworkInfo, 102 }; 103}; 104 105export default useNetworkInformation; 106