npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

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

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.

npm version License: MIT Sponsor TypeScript


✨ 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), and rtt (latency).
  • 🔔 Reconnection Callbacks — Fire onOnline, onOffline, and onChange hooks 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-react

or 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