Skip to content

Instantly share code, notes, and snippets.

@beratdogan
Created February 15, 2019 20:34
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save beratdogan/f6030b41c3a5d0728adac25458f1e6f3 to your computer and use it in GitHub Desktop.
Save beratdogan/f6030b41c3a5d0728adac25458f1e6f3 to your computer and use it in GitHub Desktop.
React Hooks with Context API Example
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