JAVASCRIPT
React `useOnlineStatus` Hook for Network Connectivity Detection
A custom React hook to detect and manage the user's online or offline network connectivity status, enabling adaptive UI/UX based on network availability for better user experience.
import { useState, useEffect } from 'react';
function useOnlineStatus() {
const [isOnline, setIsOnline] = useState(navigator.onLine);
useEffect(() => {
const handleOnline = () => setIsOnline(true);
const handleOffline = () => setIsOnline(false);
window.addEventListener('online', handleOnline);
window.addEventListener('offline', handleOffline);
return () => {
window.removeEventListener('online', handleOnline);
window.removeEventListener('offline', handleOffline);
};
}, []);
return isOnline;
}
export default useOnlineStatus;
How it works: This `useOnlineStatus` hook leverages browser `online` and `offline` events to track the network connectivity status. It initializes its state based on `navigator.onLine` and updates it whenever the network status changes. This is incredibly useful for building resilient applications that can adapt their UI or functionality based on whether the user has an active internet connection.