useOnlineStatus
React hook to check if the user is online.
Made by lucasConnection status :Offline
"use client";
import React from "react";
// On suppose que le hook est importable ainsi, sinon ajuster le chemin :
import useOnlineStatus from "@/components/targetblank/hooks/use-online-status";
import { cn } from "@/lib/utils";
const OnlineStatusDemo: React.FC = () => {
const isOnline = useOnlineStatus();
return (
<div className="flex items-center gap-2">
<div
className={cn(
"size-1.5 rounded-full",
isOnline ? "bg-green-400" : "bg-red-400",
)}
/>
<span className="text-sm text-muted-foreground">Connection status :</span>
<span
className={cn(
"text-sm font-medium",
isOnline ? "text-green-500" : "text-red-500",
)}
>
{isOnline ? "Online" : "Offline"}
</span>
</div>
);
};
export default OnlineStatusDemo;
Installation
Install the following dependencies:
Copy and paste the following code into your project:
import * as React from "react";
function useOnlineStatus(): boolean {
const [isOnline, setIsOnline] = React.useState(() =>
typeof navigator !== "undefined" ? navigator.onLine : true,
);
const handleOnline = React.useCallback(() => setIsOnline(true), []);
const handleOffline = React.useCallback(() => setIsOnline(false), []);
React.useEffect(() => {
window.addEventListener("online", handleOnline);
window.addEventListener("offline", handleOffline);
return () => {
window.removeEventListener("online", handleOnline);
window.removeEventListener("offline", handleOffline);
};
}, [handleOffline, handleOnline]);
return isOnline;
}
export default useOnlineStatus;
Update the import paths to match your project setup.
Usage
const isOnline = useOnlineStatus();
Props
Prop | Type | Default |
---|---|---|
isOnline? | boolean | - |