React Dojo

Search

Search concepts, exercises and quizzes

dom

useOnlineStatus

Tracks whether the user is connected to the internet by listening to the browser's online and offline events.


useOnlineStatus.ts
import { useSyncExternalStore } from "react"

function subscribe(callback: () => void) {
  window.addEventListener("online", callback)
  window.addEventListener("offline", callback)
  return () => {
    window.removeEventListener("online", callback)
    window.removeEventListener("offline", callback)
  }
}

export function useOnlineStatus(): boolean {
  return useSyncExternalStore(
    subscribe,
    () => navigator.onLine,
    () => true
  )
}
Was this helpful?
Sign in to give feedback