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

@arindam-stack/react-network-status

v0.0.1

Published

Production-ready React package for detecting internet status and handling online/offline UI

Readme

@arindam-stack/react-network-status

npm version npm downloads License: MIT

A production-ready TypeScript React package for detecting internet status and handling online/offline UI with zero dependencies.

Features

  • 🌐 Real-time Network Detection - Instantly detect online/offline status
  • SSR Safe - Works seamlessly with server-side rendering
  • 📦 Zero Dependencies - Lightweight and minimal bundle size
  • 🎨 UI Components - Pre-built banner and guard components
  • 🔄 Auto-Retry - Automatic request retry when network is restored
  • 📊 Connection Info - Access connection type and speed (when available)
  • 🎯 TypeScript - Fully typed for maximum developer experience
  • Accessible - WCAG compliant components with proper ARIA labels

Installation

npm install @arindam-stack/react-network-status

Or with yarn:

yarn add @arindam-stack/react-network-status

Or with pnpm:

pnpm add @arindam-stack/react-network-status

Quick Start

Basic Usage with Hook

import { useNetworkStatus } from '@arindam-stack/react-network-status';

function App() {
  const { isOnline } = useNetworkStatus();

  return (
    <div>
      {isOnline ? '✓ Online' : '✗ Offline'}
    </div>
  );
}

Using the Banner Component

import { NetworkBanner } from '@arindam-stack/react-network-status';

function App() {
  return (
    <>
      <NetworkBanner
        offlineText="⚠️ No internet connection"
        onlineText="✓ You are back online"
        position="top"
      />
      {/* Your app content */}
    </>
  );
}

Protecting Features with OfflineGuard

import { OfflineGuard } from '@arindam-stack/react-network-status';

function App() {
  return (
    <OfflineGuard fallback={<p>Payment unavailable offline</p>}>
      <PaymentForm />
    </OfflineGuard>
  );
}

Auto-Retry Failed Requests

import { useRetryRequest } from '@arindam-stack/react-network-status';

function DataFetcher() {
  const { execute, data, isLoading, error, isRetryPending } = useRetryRequest({
    maxRetries: 5,
    retryDelay: 2000,
    onRetrySuccess: () => console.log('Request succeeded on retry'),
  });

  const handleFetch = async () => {
    await execute(async () => {
      const response = await fetch('/api/data');
      if (!response.ok) throw new Error('API error');
      return response.json();
    });
  };

  return (
    <div>
      <button onClick={handleFetch} disabled={isLoading}>
        {isLoading ? 'Loading...' : 'Fetch Data'}
      </button>
      {isRetryPending && <p>Retrying when connection restored...</p>}
      {error && <p>Error: {String(error)}</p>}
      {data && <pre>{JSON.stringify(data, null, 2)}</pre>}
    </div>
  );
}

Hooks API

useNetworkStatus()

Detect current internet connectivity status.

Returns:

{
  isOnline: boolean;              // Current online status
  wasOffline: boolean;            // True when reconnecting after offline
  connectionType: string;         // Network type: wifi, 4g, cellular, etc.
  downlink: number | null;        // Connection speed in Mbps (when available)
  sinceOffline: number | null;    // Timestamp (ms) when went offline, null if online
}

Example:

const { isOnline, wasOffline, connectionType, downlink, sinceOffline } = useNetworkStatus();

if (wasOffline) {
  console.log(`Back online! Was offline for ${Date.now() - sinceOffline}ms`);
}

if (connectionType === 'wifi') {
  console.log(`Connected via WiFi at ${downlink} Mbps`);
}

useRetryRequest(options)

Execute async functions with automatic retry on network failure.

Options:

| Option | Type | Default | Description | |--------|------|---------|-------------| | maxRetries | number | 3 | Maximum retry attempts | | retryDelay | number | 1000 | Delay between retries (ms) | | onRetrySuccess | function | - | Callback when retry succeeds | | onRetryFailure | function | - | Callback when all retries fail |

Returns:

{
  isLoading: boolean;          // Request in progress
  data: T | null;              // Successful response data
  error: unknown | null;       // Last error
  retryCount: number;          // Current retry attempt
  isRetryPending: boolean;     // Waiting for network to return online
  execute: (fn) => Promise<T>; // Execute the async function
}

Example:

const { execute, data, isLoading, error, isRetryPending } = useRetryRequest({
  maxRetries: 5,
  retryDelay: 2000,
  onRetrySuccess: () => toast.success('Synced!'),
  onRetryFailure: (err) => toast.error(`Sync failed: ${err}`),
});

const syncData = async () => {
  await execute(async () => {
    const res = await fetch('/api/sync', { method: 'POST' });
    if (!res.ok) throw new Error(res.statusText);
    return res.json();
  });
};

Components API

NetworkBanner

Display banner notifications for online/offline status changes.

Props:

| Prop | Type | Default | Description | |------|------|---------|-------------| | offlineText | string | "You are offline" | Text shown when offline | | onlineText | string | "You are back online" | Text shown on reconnect | | position | "top" | "bottom" | "top" | Banner position on screen | | className | string | "" | Additional CSS classes | | autoHideDuration | number | 3000 | Auto-hide delay in ms (online message only) |

Example:

<NetworkBanner
  offlineText="🚫 No Internet Connection"
  onlineText="✅ Connection Restored"
  position="bottom"
  className="custom-banner"
  autoHideDuration={5000}
/>

OfflineGuard

Conditionally render content based on network status.

Props:

| Prop | Type | Description | |------|------|-------------| | children | ReactNode | Content to show when online | | fallback | ReactNode | Content to show when offline |

Example:

<OfflineGuard fallback={<p>Feature unavailable offline</p>}>
  <StripeCheckout />
</OfflineGuard>

<OfflineGuard
  fallback={
    <div className="offline-placeholder">
      <p>Data syncing will resume when online</p>
    </div>
  }
>
  <RealtimeCollaboration />
</OfflineGuard>

Advanced Usage

Multiple Banners

function App() {
  const { isOnline } = useNetworkStatus();

  return (
    <>
      {!isOnline && (
        <NetworkBanner position="top" offlineText="No Connection" />
      )}
      <NetworkBanner position="bottom" />
      {/* App content */}
    </>
  );
}

Custom Hook Combination

function SyncedComponent() {
  const { isOnline } = useNetworkStatus();
  const { execute, isLoading, error } = useRetryRequest();

  useEffect(() => {
    if (isOnline && pendingUpdates.length > 0) {
      execute(() => syncPendingUpdates());
    }
  }, [isOnline]);

  return (
    <OfflineGuard fallback={<p>Changes will sync when online</p>}>
      {/* Content */}
    </OfflineGuard>
  );
}

With Error Handling

const { execute, data, error, isRetryPending } = useRetryRequest({
  maxRetries: 3,
  retryDelay: 1000,
  onRetryFailure: (err) => {
    if (err instanceof TypeError) {
      // Network error
      logError('Network request failed', err);
    } else {
      // Other error
      logError('Request failed', err);
    }
  },
});

Browser Support

  • Chrome ✓
  • Firefox ✓
  • Safari ✓
  • Edge ✓
  • IE 11+ ✓ (with polyfills)

Network Information API

The useNetworkStatus hook provides enhanced connection details via the Network Information API:

  • connectionType: Current network type
  • downlink: Estimated effective bandwidth (Mbps)

These values may be null if the Network Information API is not available in the user's browser.

TypeScript

Full TypeScript support with exported types:

import type {
  NetworkStatus,
  UseRetryRequestOptions,
  RetryRequestState,
  NetworkBannerProps,
  OfflineGuardProps,
} from '@arindam-stack/react-network-status';

Performance

  • Minimal bundle size (~3KB gzipped)
  • Zero external dependencies
  • Optimized event listeners with cleanup
  • SSR-safe implementation

License

MIT © 2024