Created
February 15, 2019 20:34
-
-
Save beratdogan/f6030b41c3a5d0728adac25458f1e6f3 to your computer and use it in GitHub Desktop.
React Hooks with Context API Example
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
import React, {createContext, useEffect, useContext, useReducer} from 'react'; | |
const initialArgs = { | |
count: 0 | |
}; | |
const CounterContext = createContext(initialArgs); | |
function counterReducer(state, action) { | |
switch (action) { | |
case 'increase': | |
return {...state, count: state.count + 1}; | |
case 'decrease': | |
return {...state, count: state.count - 1}; | |
default: | |
throw new Error('undefined error'); | |
} | |
} | |
function CounterStore({children}) { | |
const [state, dispatch] = useReducer(counterReducer, initialArgs); | |
const value = {state, dispatch}; | |
return ( | |
<CounterContext.Provider value={value}> | |
{children} | |
</CounterContext.Provider> | |
) | |
} | |
function DisplayCount() { | |
const {state} = useContext(CounterContext); | |
useEffect(() => { | |
document.title = `You have clicked ${state.count} times.`; | |
}); | |
return ( | |
<div>You have clicked {state.count} times.</div> | |
); | |
} | |
function CountButtons() { | |
const {dispatch} = useContext(CounterContext); | |
return ( | |
<div> | |
<button onClick={() => dispatch('increase')}>+1</button> | |
<button onClick={() => dispatch('decrease')}>+1</button> | |
</div> | |
); | |
} | |
function App() { | |
return ( | |
<CounterStore> | |
<DisplayCount/> | |
<CountButtons/> | |
</CounterStore> | |
); | |
} | |
export default App; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment