Skip to content

Instantly share code, notes, and snippets.

@andeersg
Last active May 20, 2019 08:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save andeersg/1decf8b76fae6bb1af63467f32a14ef3 to your computer and use it in GitHub Desktop.
Save andeersg/1decf8b76fae6bb1af63467f32a14ef3 to your computer and use it in GitHub Desktop.
A simple React hook to get online status and listen for changes
import React, { useState } from 'react';
import useOnlineStatus from './useOnlineStatus';
const Example = () => {
const [onlineStatus, setOnlineStatus] = useState(navigator.onLine);
useOnlineStatus((isOnline) => {
setOnlineStatus(isOnline);
});
return (
<h3>This site is {onlineStatus ? 'online' : 'offline'}</h3>
);
};
export default Example;
import React, { useEffect, useRef } from 'react';
function useOnelineStatus(callback) {
const savedCallback = useRef();
useEffect(() => {
savedCallback.current = callback;
}, [callback]);
const isOnline = () => {
savedCallback.current(true);
};
const isOffline = () => {
savedCallback.current(false);
};
useEffect(() => {
savedCallback.current(navigator.onLine);
window.addEventListener('online', isOnline);
window.addEventListener('offline', isOffline);
return () => {
window.removeEventListener('online', isOnline);
window.removeEventListener('offline', isOffline);
}
}, []);
}
export default useOnelineStatus;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment