Skip to content

Instantly share code, notes, and snippets.

@tjinlag
Created July 8, 2021 09:49
Show Gist options
  • Save tjinlag/8347778499500d06a0a487ad79f55437 to your computer and use it in GitHub Desktop.
Save tjinlag/8347778499500d06a0a487ad79f55437 to your computer and use it in GitHub Desktop.
React Custom Hook: get network status - online or offline
import { useState, useEffect } from "react";
const useOnlineStatus = () => {
const [online, setOnline] = useState(true);
useEffect(() => {
const goOnline = () => setOnline(true);
const goOffline = () => setOnline(false);
window.addEventListener('online', goOnline);
window.addEventListener('offline', goOffline);
return () => {
window.removeEventListener('online', goOnline);
window.removeEventListener('offline', goOffline);
};
}, []);
return online;
};
export default useOnlineStatus;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment