Created
December 13, 2018 14:41
-
-
Save gianmarcotoso/41e32c70b0d0aa932c2490d958a32224 to your computer and use it in GitHub Desktop.
A simple `useRedux` hook to "connect" components to redux using react hooks
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
import { useState, useContext, useEffect } from 'react' | |
import { StoreContext } from '../contexts/store.context' | |
export const useRedux = (selector = state => state, mapDispatch = {}) => { | |
const store = useContext(StoreContext) | |
if (!store) { | |
throw new Error( | |
`Store not found. Wrap your application within a StoreProvider and pass it the appropriate store prop.` | |
) | |
} | |
const getState = () => selector(store.getState()) | |
const [state, setState] = useState(getState()) | |
useEffect(() => { | |
const unsubscribe = store.subscribe(() => { | |
setState(getState()) | |
}) | |
return () => { | |
unsubscribe() | |
} | |
}) | |
const mappedMethods = Object.keys(mapDispatch).reduce((r, n) => { | |
return { | |
...r, | |
[n]: (...args) => store.dispatch(mapDispatch[n].apply(undefined, args)) | |
} | |
}, {}) | |
return [state, mappedMethods, store.dispatch] | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment