🚀 Detecting Online/ Offline Status in React 🌐
Dzung Nguyen

Dzung Nguyen @dzungnt98

About: A chill software engineer

Location:
Vietnam
Joined:
Mar 7, 2021

🚀 Detecting Online/ Offline Status in React 🌐

Publish Date: Feb 18
0 0

🚀 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;
};
Enter fullscreen mode Exit fullscreen mode

And this is how you can use it:

const OnlineStatus = () => {
  const isOnline = useOnlineStatus();

  return (
    <div>
      <h2>Status: {isOnline ? "🟢 Online" : "🔴 Offline"}</h2>
    </div>
  );
};
Enter fullscreen mode Exit fullscreen mode

Follow me to stay updated with my future posts:

Comments 0 total

    Add comment