Skip to content

Instantly share code, notes, and snippets.

@marioluevanos
Last active January 9, 2019 20:42
Show Gist options
  • Save marioluevanos/adf9a4a9500af9a9107969f561679fa9 to your computer and use it in GitHub Desktop.
Save marioluevanos/adf9a4a9500af9a9107969f561679fa9 to your computer and use it in GitHub Desktop.
Functional state container that encapsulates state with closures.
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