Skip to content

Instantly share code, notes, and snippets.

@madrus
Last active May 10, 2022 07:40
Show Gist options
  • Save madrus/456307c64be8edb9f0fdb2fb555fb6ef to your computer and use it in GitHub Desktop.
Save madrus/456307c64be8edb9f0fdb2fb555fb6ef to your computer and use it in GitHub Desktop.
React: a React hook found on Internet to show the online&offline status of your app
import { FC, useState, useEffect, useContext, createContext, ReactElement } from 'react'
const OnlineStateContext = createContext<boolean>(true)
export const OnlineStateProvider: FC = ({ children }): ReactElement => {
const [onlineState, setOnlineState] = useState<boolean>(true)
useEffect(() => {
window.addEventListener('offline', () => {
setOnlineState(false)
})
window.addEventListener('online', () => {
setOnlineState(true)
})
return () => {
window.removeEventListener('offline', () => {
setOnlineState(false)
})
window.removeEventListener('online', () => {
setOnlineState(true)
})
}
}, [])
return (
<OnlineStateContext.Provider value={onlineState}>
{children}
</OnlineStateContext.Provider>
)
}
export const useOnlineState = (): boolean => {
return useContext(OnlineStateContext)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment