Something went wrong. Try again.
[READ-ONLY] Mirror of https://github.com/wojtekmaj/react-hooks. A collection of React Hooks.
hooks react react-hooks
Something went wrong. Try again.
1.0 kB · 45 lines
TypeScript
12345678910111213141516171819202122232425262728293031323334353637383940414243444546import { useEffect, useState } from 'react';
const isBrowser = typeof window !== 'undefined';
export default function useNetworkInformation(): NetworkInformation | null { const [connection, setConnection] = useState<NetworkInformation | null>(() => { if (!isBrowser || !('connection' in navigator)) { return null; }
const connection = navigator.connection;
return connection || null; });
useEffect(() => { if (!isBrowser || !('connection' in navigator)) { return; }
const connection = navigator.connection;
if (!connection) { return; }
function onConnectionChange() { if (!isBrowser || !('connection' in navigator)) { return null; }
const connection = navigator.connection;
setConnection(connection || null); }
connection.addEventListener('change', onConnectionChange);
return () => { connection.removeEventListener('change', onConnectionChange); }; }, []);
return connection;}