Created
January 9, 2020 07:52
-
-
Save vincicat/3a667cfd6c873fbb036b12c75f7e524a to your computer and use it in GitHub Desktop.
basic useContext()
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React from 'react'; | |
import { AppProvider } from "./AppContext"; | |
import { AppContainer } from "./AppContainer"; | |
function App() { | |
return ( | |
<AppProvider> | |
<AppContainer /> | |
</AppProvider> | |
); | |
} | |
export default App; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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