Last active
March 6, 2020 18:11
-
-
Save r3dm1ke/2a446f55ebcba83d44492a5a4b12abad to your computer and use it in GitHub Desktop.
This file contains 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
// EXAMPLE WITH CONTEXT + REDUCER | |
import React, {useContext, useReducer} from 'react'; | |
const AppContext = React.createContext(null); | |
const ContextProvider = ({children}) => { | |
const reducer = (state, action) => { | |
switch (action.type) { | |
case 'INCREMENT': | |
return {...state, counter: state.counter + 1}; | |
default: | |
return state; | |
} | |
} | |
const store = useReducer(reducer, {counter: 0}); | |
return ( | |
<AppContext.Provider value={store}> | |
{children} | |
</AppContext> | |
); | |
} | |
const App = () => { | |
return ( | |
<ContextProvider> | |
<Counter /> | |
<ContextProvider/> | |
); | |
} | |
const Counter = () => { | |
const {state, dispatch} = useContext(AppContext); | |
return ( | |
<> | |
<button onClick={() => dispatch({type: 'INCREMENT'})}>Click me</button> | |
<p>You clicked me {state.counter} times</p> | |
</> | |
); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment