Skip to content

Instantly share code, notes, and snippets.

@DRFR0ST
Last active May 20, 2020 11:01
Show Gist options
  • Save DRFR0ST/b913c4a7c015e041d91482ac43d0b231 to your computer and use it in GitHub Desktop.
Save DRFR0ST/b913c4a7c015e041d91482ac43d0b231 to your computer and use it in GitHub Desktop.
🎣 React Native hook for checking internet connection.
import { useRef, useState } from 'react';
import NetInfo from "@react-native-community/netinfo";
/**
* Returns information about internet connectivity.
* @example const [isConnected, checkConnection] = useConnectivity();
*/
export const useConnectivity = () => {
const [ isConnected, setConnected ] = useState<boolean | null>(null);
const ref = useRef<[ typeof isConnected, () => void ] | null>(null);
if(ref.current === null) {
const checkConnection = () => {
NetInfo.fetch().then(state => {
setConnected(!!state.isConnected);
});
}
ref.current = [isConnected, checkConnection];
ref.current[1]();
}
ref.current[0] = isConnected;
return ref.current;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment