Skip to content

Instantly share code, notes, and snippets.

@jake-daniels
Last active November 2, 2019 15:25
Show Gist options
  • Save jake-daniels/d403415b10aebdfe2feea3c09beae6c0 to your computer and use it in GitHub Desktop.
Save jake-daniels/d403415b10aebdfe2feea3c09beae6c0 to your computer and use it in GitHub Desktop.
function initRedux(reducer, initialState) {
const StateContext = React.createContext(null)
const DispatchContext = React.createContext(null)
function Provider(props) {
const [appState, dispatch] = React.useReducer(reducer, initialState)
return (
<StateContext.Provider value={appState}>
<DispatchContext.Provider value={dispatch}>
{props.children}
</DispatchContext.Provider>
</StateContext.Provider>
)
}
function useRedux(extractState, actionMap) {
const appState = React.useContext(StateContext)
const dispatch = React.useContext(DispatchContext)
const stateExtract = extractState(appState)
const actions = Object.keys(actionMap).reduce((acc, key) => {
const actionCreator = actionMap[key]
const fn = (...args) => {
const action = actionCreator(...args)
if (typeof action === 'function') {
action(dispatch, () => appState)
} else {
dispatch(action)
}
}
return { ...acc, [key]: fn }
}, {})
return [stateExtract, actions]
}
return { Provider, useRedux }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment