Himanshu Chandola

Feb 19, 2025 • 1 min read

Building a React Hook to Detect Internet Connection (TypeScript)

Building a React Hook to Detect Internet Connection (TypeScript)

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


Monitoring Online Status in React

Let's create a custom React hook, useOnlineStatus, to track the user's online status in real-time.

Implementation

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;

Usage

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;

Summary

  • 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. 🚀

Join Himanshu on Peerlist!

Join amazing folks like Himanshu and thousands of other people in tech.

Create Profile

Join with Himanshu’s personal invite link.

2

6

1