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

react-reachability

v0.1.0

Published

Framework-agnostic network reachability detection with Web Worker support and React hook

Downloads

9

Readme

react-reachability

A framework-agnostic network reachability detection library with Web Worker support and React hook.

npm version License: MIT

Features

  • Non-blocking: Probes run in a Web Worker to avoid blocking the main thread
  • Framework-agnostic: Core ReachabilityMonitor class works with any framework
  • React hook: useReachability hook for React applications
  • SSR-safe: Returns unknown state during server-side rendering
  • Fallback URLs: Tries multiple URLs in sequence until one succeeds
  • Configurable: Timeout, interval, retries, and custom URLs
  • Zero runtime dependencies: Only peer dependency is React (optional)
  • TypeScript: Full type definitions included

Why not navigator.onLine?

navigator.onLine is unreliable—it only indicates if the device has a network interface, not actual internet connectivity. This library performs real network probes to accurately detect internet availability.

Installation

npm install react-reachability
# or
yarn add react-reachability
# or
pnpm add react-reachability

Usage

React Hook

import { useReachability } from 'react-reachability';

function NetworkStatus() {
  const { isOnline, status, lastChecked, checkNow } = useReachability({
    urls: ['https://www.google.com/generate_204'],
    interval: 30000, // Check every 30 seconds
    timeout: 5000,   // 5 second timeout per request
  });

  if (status === 'unknown' || status === 'checking') {
    return <div>Checking connection...</div>;
  }

  return (
    <div>
      <p>Status: {isOnline ? '🟢 Online' : '🔴 Offline'}</p>
      <p>Last checked: {lastChecked?.toLocaleTimeString()}</p>
      <button onClick={checkNow}>Check Now</button>
    </div>
  );
}

Vanilla JavaScript

import { ReachabilityMonitor } from 'react-reachability';

const monitor = new ReachabilityMonitor({
  urls: ['https://www.google.com/generate_204', 'https://www.cloudflare.com/cdn-cgi/trace'],
  interval: 30000,
  timeout: 5000,
  retries: 1,
});

// Subscribe to state changes
const unsubscribe = monitor.subscribe((state) => {
  console.log('Online:', state.isOnline);
  console.log('Status:', state.status);
});

// Manual check
monitor.checkNow();

// Stop monitoring
monitor.stop();

// Resume monitoring
monitor.start();

// Clean up
monitor.destroy();

API

useReachability(options?)

React hook for network reachability detection.

Options

| Option | Type | Default | Description | |--------|------|---------|-------------| | urls | string \| string[] | Default URLs | URL(s) to probe. Falls back to next URL on failure. | | timeout | number | 5000 | Timeout per request in milliseconds | | interval | number | 30000 | Polling interval in milliseconds | | retries | number | 1 | Number of retries per URL before trying next | | enabled | boolean | true | Enable/disable monitoring | | notifyOnlyOnChange | boolean | true | If true, only notify when isOnline changes. If false, notify on every probe. | | onLog | (entry: LogEntry) => void | undefined | Callback for debug logging |

Return Value

| Property | Type | Description | |----------|------|-------------| | isOnline | boolean \| null | true if online, false if offline, null if unknown | | status | 'online' \| 'offline' \| 'checking' \| 'unknown' | Current status | | lastChecked | Date \| null | Timestamp of last check | | error | Error \| null | Last error, if any | | checkNow | () => void | Trigger immediate check |

ReachabilityMonitor

Core class for vanilla JavaScript usage.

Constructor

new ReachabilityMonitor(options?: ReachabilityOptions)

Methods

| Method | Description | |--------|-------------| | start() | Start monitoring | | stop() | Stop monitoring | | checkNow() | Trigger immediate check | | subscribe(listener) | Subscribe to state changes. Returns unsubscribe function. | | getState() | Get current state | | updateConfig(options) | Update configuration | | destroy() | Clean up resources |

Default URLs

The library ships with sensible default URLs:

[
  'https://www.google.com/generate_204',
  'https://www.cloudflare.com/cdn-cgi/trace',
  'https://www.apple.com/library/test/success.html',
]

You can override these by providing your own urls option.

How It Works

  1. Web Worker: Probes run in a Web Worker to avoid blocking the main thread
  2. Fetch with no-cors: Uses fetch with mode: 'no-cors' to work cross-origin
  3. Fallback: If Worker is unavailable, falls back to main thread probing
  4. State changes only: By default, listeners are only notified when isOnline actually changes

notifyOnlyOnChange Option

By default (notifyOnlyOnChange: true), the main thread is only notified when the online/offline state changes. This is efficient and avoids unnecessary re-renders.

If you set notifyOnlyOnChange: false, the main thread will be notified after every probe interval, updating lastChecked each time.

⚠️ Warning: Setting notifyOnlyOnChange: false means the main thread callback will be invoked every interval milliseconds (default 30 seconds), which may cause unnecessary re-renders in React applications. Only use this if you need to display a continuously updating lastChecked timestamp.

Browser Support

Works in all modern browsers that support:

  • Web Workers
  • Fetch API
  • AbortController

Falls back gracefully to main-thread probing if Web Workers are unavailable.

SSR Support

The library is SSR-safe. During server-side rendering:

  • isOnline returns null
  • status returns 'unknown'
  • No network requests are made

License

MIT