Custom react hook for checking client internet connection:- useOnlineStatus
Series: Custom React Hooks
Episodes: (8/10)
- Custom React Hook for Full Screen Mode
- Custom React Hook for Queue
- Custom React Hook for Array
- Custom React Hook for Event Listening
- Custom React Hook for using setInterval
- Custom React Hook for using setTimeout
- Custom react hook for client idle detection:- useIdle
- Custom react hook for checking client internet connection:- useOnlineStatus
- Custom react hook for API call:- useAsync
- Custom React Hook for using Intersection Observer:- useIntersectionObserver
Implementation
import { useEffect, useState } from "react";
/**
* useOnlineStatus
*
* React hook that returns the current online status of the browser.
*
* @returns {{ isOnline: boolean }} Object containing the online status
*/
const useOnlineStatus = () => {
const [isOnline, setIsOnline] = useState(navigator.onLine);
/**
* useEffect
*
* Adds event listeners for online and offline events and removes them on unmount.
* Updates the online status whenever these events are fired.
*/
useEffect(() => {
/**
* updateStatus
*
* Updates the online status of the browser.
*/
const updateOnlineStatus = () => setIsOnline(navigator.onLine);
window.addEventListener("online", updateOnlineStatus);
window.addEventListener("offline", updateOnlineStatus);
return () => {
window.removeEventListener("online", updateOnlineStatus);
window.removeEventListener("offline", updateOnlineStatus);
};
}, []);
return { isOnline };
};
export default useOnlineStatus;