Created
April 25, 2019 12:50
-
-
Save sami616/35179060b5ef4dbc0011e0aa8d815248 to your computer and use it in GitHub Desktop.
Medium global state gist
This file contains hidden or 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 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