Skip to content

Instantly share code, notes, and snippets.

@reecelucas
Last active April 2, 2019 16:31
Show Gist options
  • Save reecelucas/52449286f0bca95241c0c88814e8a307 to your computer and use it in GitHub Desktop.
Save reecelucas/52449286f0bca95241c0c88814e8a307 to your computer and use it in GitHub Desktop.
Simple network connectivity hook
import { useState, useEffect } from 'react';
/**
* navigator.onLine behaves a little differently across browsers
* (https://developer.mozilla.org/en-US/docs/Web/API/NavigatorOnLine/onLine#Specification).
* For bullet-proof detection you can add to this hook using some of the suggestions
* mentioned here https://www.html5rocks.com/en/mobile/workingoffthegrid/.
*
* Usage:
* const isOnline = useNetworkConnectivity();
*/
export default () => {
const [isOnline, setIsOnline] = useState(null);
useEffect(() => {
setIsOnline(
typeof navigator.onLine === 'boolean' ? navigator.onLine : true
);
window.addEventListener('online', goOnline);
window.addEventListener('offline', goOffline);
return () => {
window.removeEventListener('online', goOnline);
window.removeEventListener('offline', goOffline);
};
}, []);
const goOnline = () => {
setIsOnline(true);
};
const goOffline = () => {
setIsOnline(false);
};
return isOnline;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment