-
Notifications
You must be signed in to change notification settings - Fork 0
useOnlineStatus
Saurav-TB-Pandey edited this page Aug 8, 2026
·
2 revisions
Tracks the browser's active network connection status dynamically. Updates in real-time if the user's internet connection drops or restores.
The simplest possible implementation.
import { useOnlineStatus } from 'react-hook-lab';
function NetworkBadge() {
const isOnline = useOnlineStatus();
return (
<div style={{ color: isOnline ? 'green' : 'red' }}>
{isOnline ? "🟢 Online" : "🔴 Offline"}
</div>
);
}Disabling functionality (like a "Save" button) when the user goes offline to prevent data loss.
import { useOnlineStatus } from 'react-hook-lab';
function SaveForm() {
const isOnline = useOnlineStatus();
const handleSave = () => {
// Simulate save
};
return (
<form>
<textarea placeholder="Write your notes here..." />
<br/>
<button onClick={handleSave} disabled={!isOnline}>
{isOnline ? "Save to Cloud" : "Reconnecting to internet..."}
</button>
</form>
);
}An exhaustive example demonstrating how to trigger side effects (like showing a toast notification) only when the status changes.
import { useOnlineStatus } from 'react-hook-lab';
import { useEffect, useRef } from 'react';
function ConnectionWatcher() {
const isOnline = useOnlineStatus();
const prevStatus = useRef(isOnline);
useEffect(() => {
if (prevStatus.current && !isOnline) {
console.warn("WARNING: Connection lost! Retrying...");
} else if (!prevStatus.current && isOnline) {
console.log("SUCCESS: Connection restored!");
}
prevStatus.current = isOnline;
}, [isOnline]);
return <div>Watch the console for connection events.</div>;
}This hook takes absolutely zero parameters.
Returns boolean:
-
trueif the browser is currently connected to the network. -
falseif the browser is completely offline. Note that during Server-Side Rendering (SSR) environments, this value strictly defaults totrue.
Built with ❤️ by Saurav-TB-Pandey. | Report an Issue | NPM