Skip to content

Instantly share code, notes, and snippets.

@agnel
Created March 8, 2022 11:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save agnel/3bbde39d949ac5437f551ec7feff1e38 to your computer and use it in GitHub Desktop.
Save agnel/3bbde39d949ac5437f551ec7feff1e38 to your computer and use it in GitHub Desktop.
useNetwork Hook in react
import { useState, useEffect } from 'react';
function getNetworkConnection() {
return (
window.navigator.connection
);
}
function getNetworkConnectionInfo() {
const connection = getNetworkConnection();
if (!connection) {
return {};
}
return {
rtt: connection.rtt,
type: connection.type,
saveData: connection.saveData,
downLink: connection.downLink,
downLinkMax: connection.downLinkMax,
effectiveType: connection.effectiveType,
};
}
function useNetwork() {
const [state, setState] = useState(() => {
return {
since: undefined,
online: navigator.onLine,
...getNetworkConnectionInfo(),
};
});
useEffect(() => {
const handleOnline = () => {
setState((prevState) => ({
...prevState,
online: true,
since: new Date().toString(),
}));
};
const handleOffline = () => {
setState((prevState) => ({
...prevState,
online: false,
since: new Date().toString(),
}));
};
const handleConnectionChange = () => {
setState((prevState) => ({
...prevState,
...getNetworkConnectionInfo(),
}));
};
window.addEventListener('online', handleOnline);
window.addEventListener('offline', handleOffline);
const connection = getNetworkConnection();
connection?.addEventListener('change', handleConnectionChange);
return () => {
window.removeEventListener('online', handleOnline);
window.removeEventListener('offline', handleOffline);
connection?.removeEventListener('change', handleConnectionChange);
};
}, []);
return state;
}
export default useNetwork;
@agnel
Copy link
Author

agnel commented Mar 8, 2022

Somehow it doesn't work in typescript.
The connection object doesn't have rrt and other variables.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment