Shadcn Hooks

useIsOnline

A hook to check if the user is online

useIsOnline

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.

use-is-online.ts
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)
}

Last updated on

On this page