Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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