Google Advertisement

React Custom Hook to Track Internet Connectivity Status Easily

Google Advertisement
🔥 Read with Full Features on Our Website

Learn how to create a custom React hook that detects online and offline status in real-time. Step-by-step explanation with code examples, ideal for all skill levels.

Published on 14 May 2025
By Priya

In today’s web apps, detecting a user’s internet connection status is crucial for a smooth user experience. Whether it’s to warn users about lost connectivity, disable submit buttons, or save data locally until reconnection — handling online/offline status can improve both reliability and UX.

🔥 Read with Full Features on Our Website

In this article, we’ll build a reusable React hook called useOnlineStatus that will help us detect the internet connectivity status of a user in real-time. We'll walk through each step in simple terms, and by the end, you’ll be able to implement this feature in any React app.


✅ What You’ll Learn:


🧠 Prerequisites

Before we start, you should be familiar with:


🏗 Step 1: Understanding the Browser API

Modern browsers provide built-in support for detecting connection status using:

navigator.onLine // true if online, false if offline

And two useful events:

These are native JavaScript features — we’ll integrate them into a React custom hook.


⚙ Step 2: Create the Custom Hook

Let’s create a file called useOnlineStatus.js in your React project’s hooks folder (or wherever you prefer).

📄 useOnlineStatus.js

import { useState, useEffect } from 'react';

function useOnlineStatus() {
  const [isOnline, setIsOnline] = useState(navigator.onLine);

  useEffect(() => {
    const handleOnline = () => setIsOnline(true);
    const handleOffline = () => setIsOnline(false);

    window.addEventListener('online', handleOnline);
    window.addEventListener('offline', handleOffline);

    // Cleanup function
    return () => {
      window.removeEventListener('online', handleOnline);
      window.removeEventListener('offline', handleOffline);
    };
  }, []);

  return isOnline;
}

export default useOnlineStatus;

✅ Explanation (Line by Line)


🧪 Step 3: Use the Hook in a Component

Now let’s use the useOnlineStatus hook inside a component to show a message based on internet connectivity.

📄 Example Component: NetworkStatus.js

import React from 'react';
import useOnlineStatus from './useOnlineStatus';

function NetworkStatus() {
  const isOnline = useOnlineStatus();

  return (
    <div style={{
      padding: '20px',
      borderRadius: '8px',
      backgroundColor: isOnline ? '#d4edda' : '#f8d7da',
      color: isOnline ? '#155724' : '#721c24',
      textAlign: 'center',
      margin: '20px auto',
      width: '300px',
      fontSize: '18px'
    }}>
      {isOnline ? '🟢 You are Online' : '🔴 You are Offline'}
    </div>
  );
}

export default NetworkStatus;

📘 What’s Happening Here?


📦 Step 4: Include the Component in Your App

Add NetworkStatus to your main App.js or any other parent component:

import React from 'react';
import NetworkStatus from './NetworkStatus';

function App() {
  return (
    <div>
      <h1>React Online/Offline Status Detector</h1>
      <NetworkStatus />
    </div>
  );
}

export default App;

Now run your app and try disconnecting/reconnecting your internet. You’ll see the status message update instantly!


💡 Real-world Use Cases

Here are some real-world ways you can use this hook:

                            Use Case                Desscription
                      📝 Form Submission                        Disable buttons when offline 
                              Data Sync                 
Queue data in local storage and sync when back online

Best Practices


🛠 Bonus: Add Toast Notifications (Optional)

Here’s how you can show toast messages when the status changes:

  1. Install react-toastify:

    npm install react-toastify
    
  1. Update your useOnlineStatus.js like this:

import { useState, useEffect } from 'react';
import { toast } from 'react-toastify';

function useOnlineStatus() {
  const [isOnline, setIsOnline] = useState(navigator.onLine);

  useEffect(() => {
    const handleOnline = () => {
      setIsOnline(true);
      toast.success("Back Online!");
    };

    const handleOffline = () => {
      setIsOnline(false);
      toast.error("You are Offline!");
    };

    window.addEventListener('online', handleOnline);
    window.addEventListener('offline', handleOffline);

    return () => {
      window.removeEventListener('online', handleOnline);
      window.removeEventListener('offline', handleOffline);
    };
  }, []);

  return isOnline;
}

Wrap your app in <ToastContainer /

import { ToastContainer } from 'react-toastify';
import 'react-toastify/dist/ReactToastify.css';

function App() {
  return (
    <>
      <ToastContainer />
      <NetworkStatus />
    </>
  );
}
 

Now you get pop-up alerts when the status changes.


🧾 Conclusion

Creating a custom React hook like useOnlineStatus allows your app to be smarter, more user-friendly, and reliable. With just a few lines of code, you can detect internet status, enhance UX, and prevent issues like failed form submissions or broken API requests.

Whether you're building a chat app, e-commerce site, or a progressive web app (PWA) — knowing when the user is offline is a powerful feature.

❤️ Like 💬 Comment 🔗 Share
Google Advertisement
👉 View Full Version on Main Website ↗
Google Advertisement
👉 Read Full Article on Website