Optimizing Offline Detection in React with Tanstack Query


Detecting when a user is offline is crucial for enhancing user experience in web applications. Whether it’s showing a helpful message or preventing unnecessary API calls, handling network loss efficiently can make your app feel more robust and user-friendly.
In this post, we'll explore a better way to detect offline status in a React application using navigator.onLine
, event listeners, and React Query (@tanstack/react-query
). We'll also improve upon a common but inefficient approach to minimize API calls.
The Problem with Basic Offline Detection
A common approach developers use to detect network status is:
Listening to
online
andoffline
events.Making API calls to confirm connectivity.
Setting state based on network response.
An Efficient Approach
An efficient way to detect offline status is by leveraging navigator.onLine
while still using React Query for periodic API checks. Here’s the optimized solution:
Optimized React Offline Detection Code
import { useQuery } from "@tanstack/react-query";
import axios from "axios";
import { useEffect, useState, ReactNode } from "react";
export default function OfflineProvider({ children }: { children: ReactNode }) {
const [offline, setOffline] = useState(!navigator.onLine);
const { refetch } = useQuery({
queryKey: ["offline"],
queryFn: async () => {
try {
const response = await axios.get("https://www.google.com");
setOffline(false);
return response.status === 200;
} catch (error) {
setOffline(true);
return false;
}
},
enabled: false, // Runs only when manually triggered
});
useEffect(() => {
const updateOnlineStatus = () => {
setOffline(!navigator.onLine);
if (navigator.onLine) {
refetch(); // Only check API when back online
}
};
window.addEventListener("online", updateOnlineStatus);
window.addEventListener("offline", updateOnlineStatus);
return () => {
window.removeEventListener("online", updateOnlineStatus);
window.removeEventListener("offline", updateOnlineStatus);
};
}, [refetch]);
return (
<>
{children}
{offline && (<p>User is offline</p>)}
</>
);
}
Why This Approach Is Better
✅ Uses navigator.onLine
for immediate detection – This avoids waiting for an API call to determine connectivity.
✅ Minimizes unnecessary API requests – We only check the API when the user goes back online, ensuring we don’t flood the server with requests.
✅ Uses React Query’s - This keeps the state clean and avoids unnecessary state updates.
✅ Ensures accurate detection – navigator.onLine
is checked first, reducing the chance of false negatives due to API downtime.
Final Thoughts
By implementing this optimized offline detection method, you improve user experience while reducing server load. This approach ensures your app stays responsive even in fluctuating network conditions.
Thank you for joining me on this technical journey. Your support and interest mean the world to me. I look forward to sharing more insightful content with you in the future. Until then, stay curious and keep exploring!
Subscribe to my newsletter
Read articles from Chilo Maximillian directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by

Chilo Maximillian
Chilo Maximillian
I am a Software Engineer from Nigeria. I have over 5 years of experience in Frontend Engineering and I have 2 years of experience working with AWS and GCP.