Skip to content

Instantly share code, notes, and snippets.

@jeffrafter
Forked from patrickcze/useOnlineStatus.tsx
Last active August 18, 2023 12:57
Show Gist options
  • Save jeffrafter/8bab08f3efaac5e8a9350cd9dc05b3cc to your computer and use it in GitHub Desktop.
Save jeffrafter/8bab08f3efaac5e8a9350cd9dc05b3cc to your computer and use it in GitHub Desktop.
A basic hook to indicate if the user is online or offline
import React, { useState, useEffect, useContext } from "react"
const OnlineStatusContext = React.createContext(true)
type Props = {
children: React.ReactNode
}
export const OnlineStatusProvider: React.FC<Props> = ({ children }) => {
const [onlineStatus, setOnlineStatus] = useState<boolean>(typeof navigator !== "undefined" ? navigator.onLine : false)
const setOnline = () => setOnlineStatus(true)
const setOffline = () => setOnlineStatus(false)
useEffect(() => {
window.addEventListener("offline", setOffline)
window.addEventListener("online", setOnline)
return () => {
window.removeEventListener("offline", setOffline)
window.removeEventListener("online", setOnline)
}
}, [])
return <OnlineStatusContext.Provider value={onlineStatus}>{children}</OnlineStatusContext.Provider>
}
export const useOnlineStatus = () => {
const store = useContext(OnlineStatusContext)
return store
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment