Skip to content

Instantly share code, notes, and snippets.

@gisderdube
Created February 6, 2019 15:22
Show Gist options
  • Save gisderdube/f9c7e0357217209a608926253b6fa3e4 to your computer and use it in GitHub Desktop.
Save gisderdube/f9c7e0357217209a608926253b6fa3e4 to your computer and use it in GitHub Desktop.
// 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