Handling Network Status in Your React App

Handling Network Status in Your React App

So picture this, yaar — we’ve got a web app that totally depends on the backend server for data. Like, full-time dependency. Tables, lists, whatever… all coming from the backend. Now obviously, we want the data to be fresh all the time — so we think, “Chalo, let’s do polling every few seconds.”

But here's the catch — suppose the user’s internet goes off for some reason. At that moment, if our API call returns nothing and we blindly store it in the React state — bam! Empty screen. All your data is gone. Looks broken.

And we don’t want that. Instead of showing blank tables and confusing the user, better to just say it straight — "No internet connection" or "You're offline, bro!"

So the idea is: let's create a wrapper component. Wrap your root-level or entry component inside it. This wrapper will keep track of the network status using the good old navigator.onLine API. If the internet is gone, we show a custom message. If it’s back, everything works as usual.

Enough gyaan — here's the code:

// NetworkStatusWrapper.js
import React, { useEffect, useState } from "react";

const NetworkStatusWrapper = ({ children }) => {
  const [isOnline, setIsOnline] = useState(navigator.onLine);

  const updateOnlineStatus = () => {
    setIsOnline(navigator.onLine);
  };

  useEffect(() => {
    window.addEventListener("online", updateOnlineStatus);
    window.addEventListener("offline", updateOnlineStatus);

    return () => {
      window.removeEventListener("online", updateOnlineStatus);
      window.removeEventListener("offline", updateOnlineStatus);
    };
  }, []);

  if (!isOnline) {
    return (
      <div style={{ padding: "2rem", textAlign: "center", color: "#d32f2f" }}>
        <h2>No Internet Connection</h2>
        <p>You're offline. Please check your connection and try again.</p>
      </div>
    );
  }

  return <>{children}</>;
};

export default NetworkStatusWrapper;        

How to use it:

// App.js
import React from "react";
import NetworkStatusWrapper from "./NetworkStatusWrapper";
import MainApp from "./MainApp"; // your actual app component

const App = () => {
  return (
    <NetworkStatusWrapper>
      <MainApp />
    </NetworkStatusWrapper>
  );
};

export default App;        

Here is the demo:

Article content

This way, even if your backend gives nothing due to no network, your app doesn't look broken — it looks smart 😎

Happy coding!

👨💻 Want more coding insights? Don’t forget to subscribe to my YouTube channel, Apni Coding, where I dive into tutorials, tips, and tricks to level up your skills. For premium courses and the latest coding blogs, visit ApniCoding.in!

Stay connected! 👉 Follow me on LinkedIn for updates on coding, tutorials, and career tips.

#linkedin #ApniCoding #LearnToCode #CodingTips #DeveloperLife

To view or add a comment, sign in

More articles by Vivek Kumar

Explore content categories