typescriptintermediate
useNetworkSpeed Hook
Monitors the Network Information API to report connection type, downlink speed, and effective type.
typescriptPress ⌘/Ctrl + Shift + C to copy
import { useState, useEffect } from 'react';
interface NetworkInfo {
effectiveType: string;
downlink: number;
rtt: number;
saveData: boolean;
online: boolean;
}
export function useNetworkSpeed(): NetworkInfo {
const getInfo = (): NetworkInfo => {
const conn = (navigator as unknown as { connection?: {
effectiveType: string; downlink: number; rtt: number; saveData: boolean;
}}).connection;
return {
effectiveType: conn?.effectiveType ?? 'unknown',
downlink: conn?.downlink ?? 0,
rtt: conn?.rtt ?? 0,
saveData: conn?.saveData ?? false,
online: navigator.onLine,
};
};
const [info, setInfo] = useState(getInfo);
useEffect(() => {
const conn = (navigator as unknown as { connection?: EventTarget }).connection;
const handler = () => setInfo(getInfo());
conn?.addEventListener('change', handler);
window.addEventListener('online', handler);
window.addEventListener('offline', handler);
return () => {
conn?.removeEventListener('change', handler);
window.removeEventListener('online', handler);
window.removeEventListener('offline', handler);
};
}, []);
return info;
}Use Cases
- Adaptive media quality
- Offline indicators
Tags
Related Snippets
Similar patterns you can reuse in the same workflow.
typescriptbeginner
useDebounce — Debounced Value Hook
Debounce any rapidly-changing value with a configurable delay. Useful for search inputs and resize handlers.
Best for: Search-as-you-type
#hooks#debounce
typescriptintermediate
Infinite Scroll with Intersection Observer
Load more items as the user scrolls using IntersectionObserver. No external libraries required.
Best for: Feed pagination
#infinite-scroll#intersection-observer
typescriptintermediate
React Intersection Observer Hook
Custom useIntersectionObserver hook for lazy loading, infinite scroll, and scroll animations.
Best for: Lazy loading components when they enter viewport
#react#hooks
typescriptintermediate
useThrottle Hook for Rate Limiting
Throttle rapidly-firing values like scroll or resize events with a configurable delay hook.
Best for: Scroll position tracking
#react#hooks