
Wondering how to determine whether a user is online or offline in your React app? With the navigator.onLine property, it's easier than you think!
For more details, check out the official documentation:
🔗 MDN Web Docs – Navigator.onLine
Let's create a custom React hook, useOnlineStatus, to track the user's online status in real-time.
import { useState, useEffect } from "react";
const useOnlineStatus = (): boolean => {
const [isOnline, setIsOnline] = useState<boolean>(navigator.onLine);
useEffect(() => {
const updateStatus = () => setIsOnline(navigator.onLine);
window.addEventListener("online", updateStatus);
window.addEventListener("offline", updateStatus);
return () => {
window.removeEventListener("online", updateStatus);
window.removeEventListener("offline", updateStatus);
};
}, []);
return isOnline;
};
export default useOnlineStatus;
Now, let's create a simple component that displays the user's online status.
import React from "react";
import useOnlineStatus from "./useOnlineStatus";
const OnlineStatus: React.FC = () => {
const isOnline = useOnlineStatus();
return (
<div>
<h2>
Status: {isOnline ? "🟢 Online" : "🔴 Offline"}
</h2>
</div>
);
};
export default OnlineStatus;
useOnlineStatus listens for online and offline events.
It updates the state whenever the user's network status changes.
The OnlineStatus component displays the current status dynamically.
This hook is lightweight and reusable, making it a great addition to any React project. 🚀
2
6
1