Uses HTML5
offline
andonline
events combined with the @Sindresorhusis-online
package for accurate online/offline detection.
- Uses
is-online
for accurate online/offline detection. - Works just about everywhere
window
is available, including Electron. - Does not require
navigator.onLine
- Works on both the client and server
Using NPM:
npm install react-is-online-context
import { IsOnlineContextProvider } from "react-is-online-context";
import { ComponentUsingContext } from "./ComponentUsingContext";
const AppComponent = () => {
// See is-online for options: https://github.com/sindresorhus/is-online
const options = {
// timeout: 5000,
};
return (
<IsOnlineContextProvider {...options}>
<ComponentUsingContext />
</IsOnlineContextProvider>
);
};
// ./ComponentUsingContext
import { IsOnlineContext } from "react-is-online-context";
export const ComponentUsingContext = (props) => {
const { isOnline, isLoading, error } = React.useContext(IsOnlineContext);
return (
<div>
{isOnline ? "You are online" : "You are offline"}
</div>
);
};
import { useIsOnline } from "react-is-online-context";
export const ComponentUsingHooks = (props) => {
const { isOnline, isLoading, error } = useIsOnline();
return (
<div>
{isOnline ? "You are online" : "You are offline"}
</div>
);
};
The IsOnlineContextProvider
component is a React Context Provider that provides the IsOnlineContext
to all of its children.
The IsOnlineContext
is a React Context that provides the following values:
-
isOnline
- A boolean indicating if the user is online or not. -
isLoading
- A boolean indicating if theisOnline
value is still being determined. -
error
- An error object if there was an error determining theisOnline
value.
The useIsOnline
hook provides the same values as the IsOnlineContext
:
-
isOnline
- A boolean indicating if the user is online or not. -
isLoading
- A boolean indicating if theisOnline
value is still being determined. -
error
- An error object if there was an error determining theisOnline
value.
A hook is reinitialized in every component that uses it. This means that if you have multiple components that use the hook, they will all have their own instance of the hook. A context is initialized once and can be used by multiple components.
navigator.onLine
is not reliable. It only tells you if the browser is currently connected to the network. It does not tell you if the user is able to reach your site. For example, the user could be connected to a wifi network, but the wifi network could be down, or the ISP could be down. Often a virtual machine will report that it is online, but it is not able to reach the internet. is-online
checks if the user is able to reach the internet by pinging a few different servers. This is a much more reliable way to check if the user is online.
Thanks to Sindresorhus for his is-online
package.