@arindam-stack/react-network-status
v0.0.1
Published
Production-ready React package for detecting internet status and handling online/offline UI
Maintainers
Readme
@arindam-stack/react-network-status
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-statusOr with yarn:
yarn add @arindam-stack/react-network-statusOr with pnpm:
pnpm add @arindam-stack/react-network-statusQuick 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 typedownlink: 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
