Last active
December 9, 2020 09:35
-
-
Save mkhoussid/bd3a9a8bc3846f5823f429c222e0b44b to your computer and use it in GitHub Desktop.
useNetworkInfo hook written in Typescript
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// adapted from here: https://googlechrome.github.io/samples/network-information/ | |
import React from 'react'; | |
type TNetworkInfo = { | |
type: string; | |
downlink: string; | |
rtt: string; | |
downlinkMax: string; | |
effectiveType: string; | |
saveData: string; | |
}; | |
export default function useNetworkInfo(logToConsole = false): TNetworkInfo { | |
const [networkInfo, setNetworkInfo] = React.useState<TNetworkInfo>({ | |
type: '', | |
downlink: '', | |
rtt: '', | |
downlinkMax: '', | |
effectiveType: '', | |
saveData: '', | |
}); | |
React.useEffect(() => { | |
navigator['connection'].addEventListener('change', logNetworkInfo); | |
function logNetworkInfo() { | |
// Network type that browser uses | |
console.log(' type: ' + navigator['connection'].type); | |
// Effective bandwidth estimate | |
console.log(' downlink: ' + navigator['connection'].downlink + ' Mb/s'); | |
// Effective round-trip time estimate | |
console.log(' rtt: ' + navigator['connection'].rtt + ' ms'); | |
// Upper bound on the downlink speed of the first network hop | |
console.log(' downlinkMax: ' + navigator['connection'].downlinkMax + ' Mb/s'); | |
// Effective connection type determined using a combination of recently | |
// observed rtt and downlink values: ' + | |
console.log('effectiveType: ' + navigator['connection'].effectiveType); | |
// True if the user has requested a reduced data usage mode from the user | |
// agent. | |
console.log(' saveData: ' + navigator['connection'].saveData); | |
console.log(''); | |
} | |
logToConsole && logNetworkInfo(); | |
setNetworkInfo({ | |
type: navigator['connection'].type, | |
downlink: navigator['connection'].downlink, | |
rtt: navigator['connection'].rtt, | |
downlinkMax: navigator['connection'].downlinkMax, | |
effectiveType: navigator['connection'].effectiveType, | |
saveData: navigator['connection'].saveData, | |
}); | |
}, [logToConsole]); | |
return networkInfo; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
usage: