Skip to content

Instantly share code, notes, and snippets.

@sanusart
Created January 23, 2025 13:58
Show Gist options
  • Save sanusart/ef28642999d62639d8248ce8c8286772 to your computer and use it in GitHub Desktop.
Save sanusart/ef28642999d62639d8248ce8c8286772 to your computer and use it in GitHub Desktop.
is online hook #react #hooks
import { useEffect, useState } from 'react';
export const useIsOnline = () => {
const [online, setOnline] = useState<boolean>(true);
const checkOnlineStatus = () => setOnline(navigator.onLine);
useEffect(() => {
window.addEventListener('online', checkOnlineStatus);
window.addEventListener('offline', checkOnlineStatus);
return () => {
window.removeEventListener('online', checkOnlineStatus);
window.removeEventListener('offline', checkOnlineStatus);
};
}, []);
return online;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment