Last active
January 9, 2019 20:42
-
-
Save marioluevanos/adf9a4a9500af9a9107969f561679fa9 to your computer and use it in GitHub Desktop.
Functional state container that encapsulates state with closures.
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
const useReducer = (reducer, initState = {}) => { | |
let state = initState; | |
const getState = () => state; | |
const dispatch = action => (state = reducer(state, action)); | |
return Object.freeze({ getState, dispatch }); | |
}; | |
const reducer = (state, action) => { | |
const actions = { | |
increment: { count: state.count + 1 }, | |
decrement: { count: state.count - 1 } | |
}; | |
return actions[action.type] || state; | |
}; | |
const makeCounter = () => { | |
const { getState, dispatch } = useReducer(reducer, { count: 0 }); | |
const get = () => getState().count; | |
const inc = () => dispatch({ type: "increment" }); | |
const dec = () => dispatch({ type: "decrement" }); | |
return Object.freeze({ get, inc, dec }); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment