Created
February 6, 2019 15:22
-
-
Save gisderdube/f9c7e0357217209a608926253b6fa3e4 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
// NOT REAL | |
// Context.js | |
export const CountContext = React.createContext(0) | |
// Counter.js | |
import { CountContext } from './Count' | |
function Counter() { | |
const [count, setCount] = useContext(CountContext) | |
return ( | |
<div> | |
<h1>The current count is {count}</h1> | |
<button onClick={() => setCount(count + 1)}>Increase count</button> | |
</div> | |
) | |
} | |
// OR WITH REDUCERS | |
// Context.js | |
export const CountContext = React.createReducerContext((state, action) => { | |
if(action.type === 'increment') return {count: state.count + 1} | |
if(action.type === 'decrement') return {count: state.count + 1} | |
return state | |
}, {count: 0}) | |
// Counter.js | |
import { CountContext } from './Count' | |
function Counter() { | |
const [state, dispatch] = useContext(CountContext) | |
return ( | |
<div> | |
<h1>The current count is {state.count}</h1> | |
<button onClick={() => dispatch({type: 'increment'})}>Increase count</button> | |
</div> | |
) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment