Create a useIsOnline React hook
There are two browser features that enable you to detect an internet connection with JavaScript:
- The Navigator interface’s
onLine
property for the current state - The
online
andoffline
events for state changes
By combining these, we can create a custom React hook that tells us if the browser is currently online.
import * as React from "react";
// Check if window is available
const maybeWindow = typeof window === "undefined" ? null : window;
export default function useIsOnline() {
const [isOnline, setIsOnline] = React.useState(
// Read onLine value from navigator if available, otherwise fallback to true
maybeWindow?.navigator.onLine ?? true
);
useEffect(() => {
// Add event listeners on mount
maybeWindow?.addEventListener("online", () => setIsOnline(true));
maybeWindow?.addEventListener("offline", () => setIsOnline(false));
// Remove event listeners on unmount
return () => {
maybeWindow?.removeEventListener("online", () => setIsOnline(true));
maybeWindow?.removeEventListener("offline", () => setIsOnline(false));
};
}, []);
// Return the online status
return isOnline;
}
We can use this hook to display a banner when the user is running our app and then goes offline:
function App() {
const isOnline = useIsOnline();
return (
<>
{!isOnline && (
<div role="alert">
You are offline. Changes will be synced when you reconnect.
</div>
)}
{/* ... */}
<>
)
}
In newer versions of React you can
use a hook like useOnline
which
depends on
useSyncExternalStore
.