Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

useContext in React Native

I've been trying to use the context hook in React Native, but it doesn't seem to work, it returns undefined. However, when I use <Context.Consumer> it does work fine, do you know if useContext is supported in React Native?

like image 484
Érik Monjas Avatar asked Dec 23 '22 21:12

Érik Monjas


1 Answers

useContext is absolutely supported in react native. Use React.createContext() to create the context.

export const AppStateContext = React.createContext();

const AppStateProvider = props => {

  const contextValue={...yourContext}

  return (
    <AppStateContext.Provider value={contextValue}>
      {props.children}
    </AppStateContext.Provider>
  );
};

Wrap your app like so.

<AppStateProvider>
    <App />
</AppStateProvider>

Then you can access the context in your nested component with the useContext hook.

import {AppStateContext} from './AppStateProvider';

function YourComponent(props) {
  const {context} = useContext(AppStateContext)
  
  ...
    return (
      <View>
      ...
      </View>
  );
}
like image 75
Antonio Pellegrini Avatar answered Dec 31 '22 03:12

Antonio Pellegrini