useOffline
Reaction hook to track if user is offline or not.
Add the hook via the CLI:
sh
npx @novajslabs/cli add useOffline
sh
npx @novajslabs/cli add useOffline
sh
pnpm dlx @novajslabs/cli add useOffline
Or copy and paste the code into your project:
ts
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);
};
js
import { useSyncExternalStore } from "react";
export const useOffline = () => {
const getSnapshot = () => !navigator.onLine;
const subscribe = (callback) => {
const handleNetworkChange = () => callback();
window.addEventListener("online", handleNetworkChange);
window.addEventListener("offline", handleNetworkChange);
return () => {
window.removeEventListener("online", handleNetworkChange);
window.removeEventListener("offline", handleNetworkChange);
};
};
return useSyncExternalStore(subscribe, getSnapshot);
};
Requirements
React 18.0 or higher
Return values
offline
Type: boolean
Represents whether the user is offline (true
) or online (false
).