Skip to main content

useNetwork

A custom hook that subscribes to the browser's network connection status using useSyncExternalStore and returns whether the device is online.

You can provide onlineCallback and offlineCallback to invoke custom functions when the network status changes.


Code​

🔗 View source code


Interface​

typescript
interface UseNetworkProps {
onlineCallback?: (event: Event) => void;
offlineCallback?: (event: Event) => void;
}

const useNetwork: ({ onlineCallback, offlineCallback }?: UseNetworkProps) => {
isOnline: boolean;
};

Options​

NameTypeDefaultDescription
onlineCallback(event: Event) => void-Callback invoked when the network transitions to an online state
offlineCallback(event: Event) => void-Callback invoked when the network transitions to an offline state

Returns​

NameTypeDescription
isOnlinebooleanWhether the network is currently online

Remarks​


Usage​

typescript
import { useNetwork } from '@modern-kit/react';

const Example = () => {
const { isOnline } = useNetwork({
onlineCallback: () => {
alert('online');
},
offlineCallback: () => {
alert('offline');
},
});

return (
<div>
<p>Try toggling the network in the Network tab of your browser's DevTools.</p>
<p>{isOnline ? '🟢 online' : '❌ offline'}</p>
</div>
);
};

Example​

Try toggling the network in the Network tab of your browser's DevTools.

❌ Offline