How to display connectivity status
This example demonstrates how to display connectivity status using the useOffline
hook.
tsx
import { useOffline } from "./useOffline";
export default function App() {
const isOffline = useOffline();
return (
<>
{isOffline ? (
<div>⚠️ You are offline. Some features may not be available.</div>
) : (
<div>✅ You are online. Everything is working as expected.</div>
)}
</>
);
}
typescript
import { useSyncExternalStore } from "react";
export const useOffline = () => {
const getSnapshot = () => !navigator.onLine;
const subscribe = (callback: () => void) => {
const handleNetworkChange = () => callback();
window.addEventListener("online", handleNetworkChange);
window.addEventListener("offline", handleNetworkChange);
return () => {
window.removeEventListener("online", handleNetworkChange);
window.removeEventListener("offline", handleNetworkChange);
};
};
return useSyncExternalStore(subscribe, getSnapshot);
};