Reaction hook to track if user is offline or not.
Add the hook via the CLI:
npx @novajslabs/cli add useOffline
Or copy and paste the code into your project:
import { useEffect, useState } from 'react'
type TUseOffline = () => boolean
export const useOffline: TUseOffline = () => {
const [offline, setOffline] = useState<boolean | null>(null)
useEffect(() => {
const handleNetworkState = () => {
setOffline(!offline)
}
addEventListener('offline', handleNetworkState)
addEventListener('online', handleNetworkState)
return () => {
removeEventListener('online', handleNetworkState)
removeEventListener('offline', handleNetworkState)
}
}, [offline])
return !!offline
}
React 16.8 or higher
- Name
offline
- Type
- boolean
- Description
Represents whether the user is offline (true) or online (false).
import { useOffline } from './hooks/useOffline'
const App = () => {
const isOffline = useOffline()
return (
<div>{isOffline ? 'You are currently offline.' : 'You are online.'}</div>
)
}
export default App
Here are some use cases where this React hook is useful:
- Displaying a message to the user when they go offline
- Preventing data submission if the user is offline
- Saving user actions locally to sync when the user goes online
- Displaying offline-specific content or UI adjustments