π Detecting Online/ Offline Status in React π
π€ Have you ever wondered how to detect if a user goes offline or back online in your React app?
π The navigator.onLine
property makes it super easy to do that!
π Documentation: https://developer.mozilla.org/en-US/docs/Web/API/Navigator/onLine
π₯ Hereβs a custom React hook (useOnlineStatus) that you can freely use for your React project π₯°
import { useState, useEffect } from "react"; const useOnlineStatus = () => { const [isOnline, setIsOnline] = useState(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; };
And this is how you can use it:
const OnlineStatus = () => { const isOnline = useOnlineStatus(); return ( <div> <h2>Status: {isOnline ? "π’ Online" : "π΄ Offline"}</h2> </div> ); };
Follow me to stay updated with my future posts:
Top comments (0)