-
-
Notifications
You must be signed in to change notification settings - Fork 3.4k
Closed
Description
I would like to propose a simple approach to integrate redux with react hooks.
The entire library code:
import { Store, Action, Dispatch } from 'redux'
import { useState, useEffect } from 'react'
export function createUseRedux <S, A extends Action> (store: Store<S, A>) {
function useRedux (): [S, Dispatch<A>]
function useRedux <T> (selector: (state: S) => T): [T, Dispatch<A>]
function useRedux (selector?: Function) {
const [state, setState] = useState(() => store.getState())
useEffect(() => store.subscribe(() => setState(store.getState())), [])
return [selector ? selector(state) : state, store.dispatch]
}
return useRedux
}
Usage:
// hooks.ts
import { createUseRedux } from 'react-redux'
import { store } from './store'
export const useRedux = createUseRedux(store)
// MyComponent.ts
import { useRedux } from './hooks'
const [value, dispatch] = useRedux(state => state.value)
Pros
- Fully typed store access (a big plus for ts users)
- Only one hook
- Very little code
Cons
- There might be some ineficiencies in the implementation
Metadata
Metadata
Assignees
Labels
No labels