useIsOnline
A React hook that tracks the browser's online/offline status and automatically updates when the connection state changes.
- Installation
- Add Source Code
npm install @plenty-hooks/use-is-online
npx @plenty-hooks/cli use-is-online
Using this command will add the source code of the hook directly to your project.
Options:
--pathor-p: Specify the directory where the hook file should be saved--kebab-caseor-k: Use kebab-case for the output filename (e.g.,use-document-title.ts). By default, the filename uses camelCase (e.g.,useDocumentTitle.ts)
Note: By adding the source code of the hook directly to your project, you won't be able to install further updates automatically. You are on your own for maintaining and updating the code.
Showcase
import useIsOnline from '@plenty-hooks/use-is-online';
function ConnectionStatus() {
const isOnline = useIsOnline();
return (
<div>
{isOnline ? (
<div>You are online</div>
) : (
<div>You are offline. Please check your connection.</div>
)}
</div>
);
}
API
useIsOnline()
Returns the current online status of the browser and automatically subscribes to online/offline events.
Returns
boolean-trueif the browser is online,falseif offline
Server-Side Rendering (SSR)
During server-side rendering the hook returns true.