Skip to content

Instantly share code, notes, and snippets.

@ourmaninamsterdam
Last active November 19, 2020 09:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ourmaninamsterdam/d92a795c4f52ddaa5bac39c06fa12615 to your computer and use it in GitHub Desktop.
Save ourmaninamsterdam/d92a795c4f52ddaa5bac39c06fa12615 to your computer and use it in GitHub Desktop.
useDeviceOnline wrapper hook for React Native's NetInfo
import NetInfo, { NetInfoState, NetInfoSubscription } from '@react-native-community/netinfo';
import { useState, useRef, useEffect } from 'react';
const useDeviceOnlineStatus = () => {
const [online, setOnline] = useState(false);
const unsubscribeRef = useRef<NetInfoSubscription | undefined>();
useEffect(() => {
unsubscribeRef.current = NetInfo.addEventListener((state: NetInfoState) => {
setOnline(state.isConnected);
});
return () => {
unsubscribeRef?.current && unsubscribeRef.current();
};
}, []);
return { online };
};
export default useDeviceOnlineStatus;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment