Skip to content

Instantly share code, notes, and snippets.

@dimitrisnl
Created April 21, 2021 20:49
Show Gist options
  • Select an option

  • Save dimitrisnl/ad27d17d6c179add724ab9e12ad7d64d to your computer and use it in GitHub Desktop.

Select an option

Save dimitrisnl/ad27d17d6c179add724ab9e12ad7d64d to your computer and use it in GitHub Desktop.
import {useEffect, useState} from 'react';
export const useNavigatorOnline = () => {
const [value, setValue] = useState(window.navigator.onLine);
useEffect(() => {
function handleOnlineStatus() {
setValue(window.navigator.onLine);
}
window.addEventListener('online', handleOnlineStatus);
window.addEventListener('offline', handleOnlineStatus);
return () => {
window.removeEventListener('online', handleOnlineStatus);
window.removeEventListener('offline', handleOnlineStatus);
};
}, []);
return {isOnline: value, isOffline: !value};
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment