use-online-status-react
v1.0.1
Published
Lightweight, SSR-safe React hook for real-time online/offline network detection with ping verification, connection metrics (4G/3G, RTT, downlink), and reconnection callbacks.
Downloads
386
Maintainers
Readme
🌐 use-online-status-react
Lightweight, SSR-safe React hook for real-time online/offline network detection with ping verification, connection metrics (4G/3G, RTT, downlink), and reconnection callbacks.
✨ Features
- ⚡ Lightweight & Zero Heavy Dependencies — Only ~2 KB minified bundle.
- 🛡️ SSR & Next.js Safe — Avoids hydration mismatch bugs in Next.js, Remix, and Gatsby.
- 📡 Ping Verification — Prevents false positives (e.g. connected to WiFi router with no actual internet connection).
- 📶 Network Quality Metrics — Reports
effectiveType('4g','3g','2g'),downlink(Mbps), andrtt(latency). - 🔔 Reconnection Callbacks — Fire
onOnline,onOffline, andonChangehooks to show toast banners or sync data. - ⚛️ React 18 & 19 Ready — Full support for modern React concurrent features.
- 📦 Dual ESM & CommonJS — Works out-of-the-box in Vite, Webpack, Turbopack, and Rollup.
📥 Installation
npm install use-online-status-reactor with Yarn / pnpm:
pnpm add use-online-status-react
# or
yarn add use-online-status-react🚀 Quick Start
1. Simple Boolean Hook (useIsOnline)
import React from 'react';
import { useIsOnline } from 'use-online-status-react';
export function NetworkIndicator() {
const isOnline = useIsOnline();
return (
<div>
{isOnline ? (
<span style={{ color: 'green' }}>● Connected</span>
) : (
<span style={{ color: 'red' }}>● You are currently offline</span>
)}
</div>
);
}2. Full Network Status & Reconnection Callbacks
import React from 'react';
import { useOnlineStatus } from 'use-online-status-react';
export function AppHeader() {
const { isOnline, effectiveType, downlink, rtt } = useOnlineStatus({
onOnline: () => {
console.log('Internet connection restored! Resyncing pending data...');
},
onOffline: () => {
console.warn('Internet lost! Working in offline mode.');
},
});
return (
<header>
{!isOnline && (
<div className="offline-banner">
⚠️ You are offline. Changes will sync once reconnected.
</div>
)}
{isOnline && effectiveType && (
<div className="network-info">
Speed: {effectiveType.toUpperCase()} ({downlink} Mbps, {rtt}ms RTT)
</div>
)}
</header>
);
}3. Active Ping Verification (Prevent WiFi False Positives)
Sometimes devices remain connected to a local WiFi router or hotspot that has no active internet access. You can specify a pingUrl to verify true connectivity:
import { useOnlineStatus } from 'use-online-status-react';
export function StatusWidget() {
const { isOnline, isPinging } = useOnlineStatus({
pingUrl: 'https://www.cloudflare.com/cdn-cgi/trace',
pingIntervalMs: 30000, // Ping every 30 seconds
pingTimeoutMs: 2500, // Timeout after 2.5s
});
return (
<div>
{isPinging && <span>Verifying connection...</span>}
<span>Status: {isOnline ? 'Online' : 'Offline'}</span>
</div>
);
}4. Standalone Non-React Helper (checkConnectivity)
Use anywhere in non-component code (e.g., Redux sagas, Axios interceptors, Zustand stores):
import { checkConnectivity } from 'use-online-status-react';
async function handleApiCall() {
const hasInternet = await checkConnectivity();
if (!hasInternet) {
throw new Error('No internet connection. Please check your network.');
}
}⚙️ Options Reference
| Option | Type | Default | Description |
|---|---|---|---|
| pingUrl | string | undefined | Endpoint to ping for verifying genuine internet reachability. |
| pingIntervalMs | number | 0 | Interval in ms for periodic background pinging (0 to disable). |
| pingTimeoutMs | number | 3000 | Timeout in ms for each ping request before considering offline. |
| onOnline | () => void | undefined | Callback fired when internet status transitions from offline to online. |
| onOffline | () => void | undefined | Callback fired when internet transitions to offline. |
| onChange | (state) => void | undefined | Callback fired on any status or metric update. |
📊 Return Value (OnlineStatusState)
| Property | Type | Description |
|---|---|---|
| isOnline | boolean | true if connected to network / internet. |
| isPinging | boolean | true while an active verification ping is in progress. |
| lastChangedAt | number | Timestamp (epoch ms) of the last status change. |
| effectiveType | '4g' \| '3g' \| '2g' \| 'slow-2g' | Network quality category (via Network Information API). |
| downlink | number | Approximate download speed in megabits per second (Mbps). |
| rtt | number | Estimated round-trip latency in milliseconds. |
| saveData | boolean | true if user enabled data saver mode in browser settings. |
🛠 Development & Testing
# Install dependencies
npm install
# Run unit tests
npm test
# Build dual ESM/CJS bundles + .d.ts types
npm run build💖 Support the Project
If you find this package useful, consider sponsoring its ongoing development and maintenance: 👉 Sponsor @Piratha97 on GitHub Sponsors
📄 License
MIT © 2026 Pirapaakaran Pirathapan
