Last active
May 10, 2022 07:40
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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