Skip to content

Instantly share code, notes, and snippets.

@vincicat
Created January 9, 2020 07:52
Show Gist options
  • Save vincicat/3a667cfd6c873fbb036b12c75f7e524a to your computer and use it in GitHub Desktop.
Save vincicat/3a667cfd6c873fbb036b12c75f7e524a to your computer and use it in GitHub Desktop.
basic useContext()
import React from 'react';
import { AppProvider } from "./AppContext";
import { AppContainer } from "./AppContainer";
function App() {
return (
<AppProvider>
<AppContainer />
</AppProvider>
);
}
export default App;
import React, {useContext} from 'react';
import { AppProvider } from "./AppContext";
function AppContainer(props){
const ctx = useContext(AppContext);
const [state, setState] = ctx;
//...
// <View> can be RN View or <div>
return (
<View>
{/* ... */}
</View>
)
}
export default AppContainer;
// React context
// https://upmostly.com/tutorials/how-to-use-the-usecontext-hook-in-react
// https://medium.com/@chathuranga94/introduction-to-react-context-api-90f5e4d7a7a9
import React, {useState} from 'react';
export const AppContext = React.createContext([{}, () => {}]);
export const AppProvider = props => {
const [state, setState] = useState({
store: {}, //simple datastore
});
return (
<AppContext.Provider value={[state, setState]}>
{props.children}
</AppContext.Provider>
);
};
// export {AppContext, AppProvider};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment