@supunlakmal/hooks
Version:
A collection of reusable React hooks
45 lines • 1.77 kB
JavaScript
import { useState, useEffect } from 'react';
const getConnectionState = (connection) => {
if (!connection) {
return {};
}
return {
downlink: connection.downlink,
downlinkMax: connection.downlinkMax,
effectiveType: connection.effectiveType,
rtt: connection.rtt,
saveData: connection.saveData,
type: connection.type,
};
};
/**
* Custom hook to get information about the user's network connection speed and type.
* Uses the experimental Network Information API (`navigator.connection`).
* Note: Browser support is limited (unavailable in Safari, Firefox behind flag).
* Information should be considered an approximation.
*
* @returns {NetworkSpeedState} An object containing network state information.
*/
export const useNetworkSpeed = () => {
const isSupported = typeof navigator !== 'undefined' && 'connection' in navigator;
const [state, setState] = useState(() => (Object.assign({ isSupported }, (isSupported ? getConnectionState(navigator.connection) : {}))));
useEffect(() => {
if (!isSupported) {
return;
}
const connection = navigator.connection;
if (!connection)
return; // Should not happen if isSupported is true, but check anyway
const handleChange = () => {
setState(Object.assign({ isSupported }, getConnectionState(connection)));
};
// Add event listener
connection.addEventListener('change', handleChange);
// Cleanup
return () => {
connection.removeEventListener('change', handleChange);
};
}, [isSupported]); // Only re-run effect if support changes (unlikely)
return state;
};
//# sourceMappingURL=useNetworkSpeed.js.map