DEV Community

Dzung Nguyen
Dzung Nguyen

Posted on

πŸš€ Detecting Online/ Offline Status in React 🌐

πŸš€ 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:

Top comments (0)