useIsOnline
A hook to check if the user is online
Loading...
Installation
npx shadcn@latest add "https://shadcn-hooks.vercel.app/r/use-is-online.json"pnpm dlx shadcn@latest add "https://shadcn-hooks.vercel.app/r/use-is-online.json"yarn dlx shadcn@latest add "https://shadcn-hooks.vercel.app/r/use-is-online.json"bun x shadcn@latest add "https://shadcn-hooks.vercel.app/r/use-is-online.json"Copy and paste the following code into your project.
import { useSyncExternalStore } from 'react'
function subscribe(onStoreChange: () => void) {
window.addEventListener('online', onStoreChange)
window.addEventListener('offline', onStoreChange)
return () => {
window.removeEventListener('online', onStoreChange)
window.removeEventListener('offline', onStoreChange)
}
}
function getSnapshot() {
return window.navigator.onLine
}
function getServerSnapshot() {
return true
}
export function useIsOnline() {
return useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot)
}API
/**
* A hook to check if the network is online
* @see https://developer.mozilla.org/en-US/docs/Web/API/Window/online_event
* @returns A boolean indicating if the network is online
*/
export function useIsOnline(): booleanLast updated on