Skip to content

Instantly share code, notes, and snippets.

@gianmarcotoso
Created December 13, 2018 14:41
Show Gist options
  • Save gianmarcotoso/41e32c70b0d0aa932c2490d958a32224 to your computer and use it in GitHub Desktop.
Save gianmarcotoso/41e32c70b0d0aa932c2490d958a32224 to your computer and use it in GitHub Desktop.
A simple `useRedux` hook to "connect" components to redux using react hooks
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