typescriptbeginner
useOnlineStatus Hook
Tracks browser online/offline status and re-renders when connectivity changes.
typescriptPress ⌘/Ctrl + Shift + C to copy
import { useSyncExternalStore } from 'react';
function subscribe(callback: () => void) {
window.addEventListener('online', callback);
window.addEventListener('offline', callback);
return () => {
window.removeEventListener('online', callback);
window.removeEventListener('offline', callback);
};
}
export function useOnlineStatus(): boolean {
return useSyncExternalStore(
subscribe,
() => navigator.onLine,
() => true // SSR fallback
);
}Use Cases
- Offline-first apps
- Connection status indicators
Tags
Related Snippets
Similar patterns you can reuse in the same workflow.
typescriptintermediate
useNetworkSpeed Hook
Monitors the Network Information API to report connection type, downlink speed, and effective type.
Best for: Adaptive media quality
#hooks#network
typescriptintermediate
useFetch — Generic Data Fetching Hook
Custom React hook for data fetching with loading, error, and refetch states using the Fetch API.
Best for: API data fetching
#hooks#fetch
typescriptbeginner
useDebounce — Debounced Value Hook
Debounce any rapidly-changing value with a configurable delay. Useful for search inputs and resize handlers.
Best for: Search-as-you-type
#hooks#debounce
typescriptintermediate
useLocalStorage — Persistent State Hook
Sync React state with localStorage including SSR safety, JSON serialization, and cross-tab updates.
Best for: User preferences
#hooks#localstorage