Skip to main content

Command Palette

Search for a command to run...

Real-Time Network Status Monitoring/checking in React with TypeScript

Efficiently Monitor and Respond to Network Connectivity in Real-Time using React and TypeScript

Published
2 min read
Real-Time Network Status Monitoring/checking in React with TypeScript
L

Greetings! I'm thrilled to share my journey as a frontend developer, where my dedication to creating memorable web experiences has been the driving force behind my success.

With a career spanning over several years in the dynamic world of web development, I've developed a profound love for crafting pixel-perfect and intuitive user interfaces. My journey began with mastering the essentials of HTML, CSS, and JavaScript, and it has evolved into embracing modern frontend frameworks like React and GraphQL to build dynamic, interactive, and user-centric applications.

I'm excited to connect with fellow developers, designers, and enthusiasts to exchange ideas and collaborate on innovative projects. Feel free to reach out to me via LinkedIn. Let's create unforgettable web experiences together!

Thank you for visiting my profile, and I look forward to exploring new frontiers in web development with you!

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.

More from this blog

L

Lakshmanan arumugam | Lead frontend engineer

31 posts

Lead Frontend Engineer | Passionate about Innovation and User-Centric Design