Skip to content

Instantly share code, notes, and snippets.

@Jahans3
Last active December 1, 2018 20:11
Show Gist options
  • Save Jahans3/b7d848204dd1a624f94e99581ce7e3c9 to your computer and use it in GitHub Desktop.
Save Jahans3/b7d848204dd1a624f94e99581ce7e3c9 to your computer and use it in GitHub Desktop.
Use state provider
export function useStateProvider ({ initialState, reducers, middleware = [] }) {
const [state, _dispatch] = useReducer((state, action) => {
return reducers.reduce((state, reducer) => reducer(state, action) || state, state);
}, initialState);
function dispatch (action) {
if (typeof action === 'function') {
return action(dispatch, state);
}
const continueUpdate = middleware.reduce((result, middleware) => {
return result !== null ? middleware(action, state) : result;
}, undefined);
if (continueUpdate !== null) {
_dispatch(action);
}
}
return { state, dispatch };
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment