useOnlineStatus
A React hook that tracks the browser's online/offline status in real-time.
Overview
useOnlineStatus monitors the browser's network connectivity status using the Navigator API's online/offline events. It also tracks whether the connection was interrupted during the current session.
Demo
API Reference
function useOnlineStatus(): {
isOnline: boolean,
wasOffline: boolean
}Returns
| Name | Type | Description |
|---|---|---|
isOnline | boolean | true if the browser is currently online. |
wasOffline | boolean | true if the connection was lost at any point during the session. |
Usage Examples
Connection Indicator
import { useOnlineStatus } from 'react-hooks-ts'
function ConnectionBadge() {
const { isOnline } = useOnlineStatus()
return (
<div className={isOnline ? 'bg-green-500' : 'bg-red-500'}>
{isOnline ? 'Online' : 'Offline'}
</div>
)
}Sync Warning
import { useOnlineStatus } from 'react-hooks-ts'
function SyncStatus() {
const { isOnline, wasOffline } = useOnlineStatus()
return (
<div>
{!isOnline && <Alert>You are offline. Changes will sync when reconnected.</Alert>}
{wasOffline && isOnline && <Alert>Reconnected! Syncing changes...</Alert>}
</div>
)
}Features
- 📡 Real-time Detection - Instantly responds to network changes.
- 🕐 Session Tracking - Knows if user went offline during the session.
- 🛡️ SSR Safe - Handles server-side rendering gracefully.
- ⚡ Lightweight - No external dependencies.