useOnlineStatus
navigator.onLine with events.
Import
TypeScript
import { useOnlineStatus } from '@/hooks';API
Signature
useOnlineStatus(defaultValue?) → boolean
When to use
Use useOnlineStatus instead of re-implementing the same pattern in multiple components.
SSR / Next.js
Returns defaults on the server; hydrates on the client.
Live playground
Edit the example and see it run against the real @/hooks package in this app.
Live playgroundEdit · run with real
@/hooks · useOnlineStatusEditor
function Banner() { const online = useOnlineStatus(); if (online) return null; return <div>You are offline</div>; }
Preview
Implementation source
Full library source for useOnlineStatus — copy into your project when you are not installing a package yet.
hooks/browser/useOnlineStatus.ts
import { useState } from 'react';
import { isBrowser, hasNavigator } from '../utility/isBrowser';
import { useEventListener } from '../events/useEventListener';
import { useIsomorphicLayoutEffect } from '../utility/useIsomorphicLayoutEffect';
/** SSR-safe online/offline status (`navigator.onLine`). */
export function useOnlineStatus(defaultValue = true): boolean {
const [online, setOnline] = useState(() =>
isBrowser() && hasNavigator() ? navigator.onLine : defaultValue,
);
useIsomorphicLayoutEffect(() => {
if (hasNavigator()) setOnline(navigator.onLine);
}, []);
useEventListener('online', () => setOnline(true));
useEventListener('offline', () => setOnline(false));
return online;
}
Copy-paste example
useOnlineStatus.example.tsx
'use client';
import { useOnlineStatus } from '@/hooks';
export function Banner() {
const online = useOnlineStatus();
if (online) return null;
return <div>You are offline</div>;
}Production checklist
- Called only from Client Components or other custom hooks
- Type parameters filled in (e.g.
useFetch<User[]>) - Tip: Values are safe during SSR (defaults). Gate layout-dependent UI with useMounted when needed.
- Source of truth: open
hooks/browser/useOnlineStatus.tsfor implementation details