useIsOnline
A hook to check if the user is online
Loading...
Installation
npx shadcn@latest add @hooks/use-is-onlinepnpm dlx shadcn@latest add @hooks/use-is-onlineyarn dlx shadcn@latest add @hooks/use-is-onlinebun x shadcn@latest add @hooks/use-is-onlineCopy 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