Skip to content

Instantly share code, notes, and snippets.

@sami616
Created April 25, 2019 12:50
Show Gist options
  • Save sami616/35179060b5ef4dbc0011e0aa8d815248 to your computer and use it in GitHub Desktop.
Save sami616/35179060b5ef4dbc0011e0aa8d815248 to your computer and use it in GitHub Desktop.
Medium global state gist
import React from 'react'
// Context
const State = React.createContext()
const Dispatch = React.createContext()
// Reducer
const reducer = (state, action) => {
switch (action.type) {
case 'increment':
return {
...state,
number: state.number + 1,
}
default:
return state
}
}
// Provider
const Provider = ({ children }) => {
const [state, dispatch] = React.useReducer(reducer, { number: 0 })
return (
<State.Provider value={state}>
<Dispatch.Provider value={dispatch}>{children}</Dispatch.Provider>
</State.Provider>
)
}
// Export
export const Counter = {
State,
Dispatch,
Provider,
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment