useNetworkStatus
Network Information API when available.
Import
TypeScript
import { useNetworkStatus } from '@/hooks';API
Signature
useNetworkStatus() → NetworkStatus
When to use
Use useNetworkStatus instead of re-implementing the same pattern in multiple components.
SSR / Next.js
Returns defaults on the server; hydrates on the client.
Live playground
Edit the example and see it run against the real @/hooks package in this app.
Live playgroundEdit · run with real
@/hooks · useNetworkStatusEditor
function Net() { const { online, effectiveType, downlink } = useNetworkStatus(); return <p>{online ? effectiveType : 'offline'} · {downlink}Mb/s</p>; }
Preview
Implementation source
Full library source for useNetworkStatus — copy into your project when you are not installing a package yet.
hooks/browser/useNetworkStatus.ts
import { useCallback, useState } from 'react';
import { hasNavigator, isBrowser } from '../utility/isBrowser';
import { useEventListener } from '../events/useEventListener';
import { useIsomorphicLayoutEffect } from '../utility/useIsomorphicLayoutEffect';
export interface NetworkStatus {
online: boolean;
downlink?: number;
effectiveType?: string;
rtt?: number;
saveData?: boolean;
}
type NetworkInformation = {
downlink?: number;
effectiveType?: string;
rtt?: number;
saveData?: boolean;
addEventListener?: (type: string, listener: () => void) => void;
removeEventListener?: (type: string, listener: () => void) => void;
};
function readNetwork(): NetworkStatus {
if (!isBrowser() || !hasNavigator()) {
return { online: true };
}
const conn = (navigator as Navigator & { connection?: NetworkInformation })
.connection;
return {
online: navigator.onLine,
downlink: conn?.downlink,
effectiveType: conn?.effectiveType,
rtt: conn?.rtt,
saveData: conn?.saveData,
};
}
/** Extended network information when supported. */
export function useNetworkStatus(): NetworkStatus {
const [status, setStatus] = useState<NetworkStatus>(readNetwork);
const update = useCallback(() => setStatus(readNetwork()), []);
useIsomorphicLayoutEffect(() => {
update();
if (!isBrowser() || !hasNavigator()) return;
const conn = (navigator as Navigator & { connection?: NetworkInformation })
.connection;
conn?.addEventListener?.('change', update);
return () => conn?.removeEventListener?.('change', update);
}, [update]);
useEventListener('online', update);
useEventListener('offline', update);
return status;
}
Copy-paste example
useNetworkStatus.example.tsx
'use client';
import { useNetworkStatus } from '@/hooks';
export function Net() {
const { online, effectiveType, downlink } = useNetworkStatus();
return <p>{online ? effectiveType : 'offline'} · {downlink}Mb/s</p>;
}Production checklist
- Called only from Client Components or other custom hooks
- Type parameters filled in (e.g.
useFetch<User[]>) - Tip: Values are safe during SSR (defaults). Gate layout-dependent UI with useMounted when needed.
- Source of truth: open
hooks/browser/useNetworkStatus.tsfor implementation details