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.
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:
-
What are browser online/offline events
-
How to use
navigator.onLine
in React -
How to build a custom hook
useOnlineStatus
-
How to use the hook in a real component
-
Best practices and real-world use cases
🧠 Prerequisites
Before we start, you should be familiar with:
-
Basics of React (
useState
,useEffect
) -
Functional components
-
JavaScript event listeners
🏗 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:
-
online
– triggered when the network is back -
offline
– triggered when the connection is lost
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)
-
useState(navigator.onLine)
initializes theisOnline
state to the browser's current connectivity status. -
useEffect(() => { ... }, [])
ensures the event listeners are added once when the component using the hook is mounted. -
handleOnline
andhandleOffline
are internal functions that update the state when connectivity changes. -
window.addEventListener('online', ...)
attaches the online event listener. -
window.addEventListener('offline', ...)
attaches the offline event listener. -
return () => {...}
removes the event listeners when the component unmounts to prevent memory leaks.
🧪 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?
-
We import our custom hook
useOnlineStatus
. -
isOnline
holds the real-time status (true/false). -
Based on the value, we change the UI’s color and message using conditional rendering.
📦 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 |
|
Best Practices
-
Avoid making unnecessary API calls when offline
-
Use localStorage or IndexedDB to store unsent data
-
Combine with a toast library (like
react-toastify
) to show real-time alerts -
Test on both desktop and mobile browsers
🛠 Bonus: Add Toast Notifications (Optional)
Here’s how you can show toast messages when the status changes:
-
Install
react-toastify
:npm install react-toastify
-
Update your
useOnlineStatus.js
like this: