@iroatu/react-network
v1.0.0
Published
Network state and connectivity utilities for React
Downloads
177
Maintainers
Readme
@iroatu/react-network
React utilities for detecting and responding to network connectivity and connection-quality changes.
Installation
pnpm add @iroatu/react-networkPeer dependency: react >= 18.
Quick Start
import { useNetwork, NetworkStatus, NetworkProvider } from '@iroatu/react-network';
function Status() {
const { isOnline, isOffline, effectiveType } = useNetwork({
onOnline: () => console.log('Back online'),
onOffline: () => console.log('Offline'),
});
if (isOffline) {
return <p>You are offline</p>;
}
return (
<p>
Online {effectiveType ? `(${effectiveType})` : ''}
</p>
);
}
function App() {
return (
<NetworkProvider>
<Status />
<NetworkStatus>
{({ isOnline }) => (!isOnline ? <div role="status">Offline banner</div> : null)}
</NetworkStatus>
</NetworkProvider>
);
}NetworkProvider is optional. useNetwork and NetworkStatus also work standalone.
API
useNetwork(options?)
Returns a NetworkState object and optionally registers transition callbacks.
| Option | Type | Description |
| --- | --- | --- |
| onOnline | () => void | Called when connectivity transitions to online (not on mount) |
| onOffline | () => void | Called when connectivity transitions to offline (not on mount) |
NetworkProvider
Optional context provider that shares a single subscription among descendants.
NetworkStatus
Render-prop component:
<NetworkStatus>
{(state) => /* ... */}
</NetworkStatus>NetworkState
type NetworkState = {
isOnline: boolean;
isOffline: boolean;
effectiveType?: 'slow-2g' | '2g' | '3g' | '4g';
downlink?: number;
rtt?: number;
saveData?: boolean;
};Optional fields come from the Network Information API and are omitted when unsupported.
Low-level helpers
getNetworkState()— snapshot without ReactsubscribeToNetwork(listener)— subscribe to change eventsisBrowserEnvironment()—typeof window !== 'undefined'
TypeScript
The package ships with generated .d.ts files. All public APIs are fully typed.
FAQ
Is navigator.onLine reliable?
It indicates browser-reported connectivity, not whether your API is reachable. Treat it as a UX signal, not a correctness guarantee.
Does this work with SSR?
Yes. On the server (no window / navigator), the package defaults to online and omits connection-quality fields. Subscribe on the client after hydration.
Will this queue requests while offline?
Not in the MVP. Offline queues and retry helpers are planned for a future release.
License
MIT
