Real-Time Network Status Monitoring/checking in React with TypeScript
Efficiently Monitor and Respond to Network Connectivity in Real-Time using React and TypeScript
Most people use to detect internet status using navigator.onLine
. but, it will not properly in some browsers and version.
For more info read the page: navigator-online-not-always-working
import { useEffect, useState } from "react";
import "./styles.css";
export default function App() {
const [isOnline, setIsOnline] = useState<boolean>(navigator.onLine);
const checkApiStatus = async () => {
try {
const response = await fetch("https://www.boredapi.com/api/activity");
setIsOnline(response.ok);
} catch (error) {
setIsOnline(false);
}
};
const checkInternetConnection = () => {
if (navigator.onLine) {
checkApiStatus();
} else {
setIsOnline(false);
}
};
useEffect(() => {
window.addEventListener("online", checkInternetConnection);
window.addEventListener("offline", checkInternetConnection);
return () => {
window.removeEventListener("online", checkInternetConnection);
window.removeEventListener("offline", checkInternetConnection);
};
}, []);
return (
<div className="container">
<h2>Internet connection status: {isOnline ? "Online" : "Offline"}</h2>
<p>Turn on/off your internet connection to see what happens</p>
{isOnline ? (
<h1 className="online">You are Online</h1>
) : (
<h1 className="offline">You are Offline</h1>
)}
</div>
);
}
In this example, we use the useState hook to manage the network status state (isOnline) with an initial value of navigator.onLine. The useEffect hook is used to add event listeners for the online and offline events. When the component is mounted, it registers the event listeners, and when the component is unmounted, it removes them to avoid memory leaks.
Whenever the network status changes, the corresponding event handler (checkInternetConnection) will be called, updating the isOnline state accordingly.
Finally, the component renders a heading displaying the current network status based on the value of isOnline.
Live example
Remember to have TypeScript properly configured in your project for this code to work.