Say I create a simple React context to check if I am connected
import NetInfo, { NetInfoState } from '@react-native-community/netinfo';
import Constants, { AppOwnership } from 'expo-constants';
import React, { PropsWithChildren, createContext, useContext, useEffect, useState } from 'react';
import { Platform } from 'react-native';
const ConnectionContext = createContext<boolean>(undefined);
export function ConnectionProvider({ children }: PropsWithChildren<any>): JSX.Element {
const [connected, setConnected] = useState(false);
function handleConnectionChange(netInfo: NetInfoState) {
setConnected(
(Platform.OS === 'ios' && Constants.appOwnership === AppOwnership.Expo) ||
(netInfo.isConnected && (netInfo.isInternetReachable ?? true))
);
}
useEffect(() => {
const subscriptionCancel = NetInfo.addEventListener(handleConnectionChange);
return () => subscriptionCancel();
}, []);
return <ConnectionContext.Provider value={connected}>{children}</ConnectionContext.Provider>;
}
export function useConnection() {
return useContext(ConnectionContext);
}
I was wondering if I want to use it in my existing component XYZ, is there a less roundabout way of doing it than the following
From:
export function XYZ() {
...xyz code...
}
to:
export function XYZ() {
return (
<ConnectionContextProvider>
<RealXyz>
</ConnectionContextProvider>
);
}
function RealXyz() {
const connected = useConnection();
...xyz code...
}
useStateinXYZright? So usually I would assume that the provider will end up wrapping a farther ancestor?