Created
November 27, 2020 20:59
-
-
Save alpox/4de7d6cbefdd535111d69b766fa9f85a to your computer and use it in GitHub Desktop.
Hook: useReduxReducer
This file contains hidden or 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
function useReduxReducer(reducer, initialState, initializer, middleware) { | |
const lastState = useRef(initialState) | |
const enhancedReducer = (state, action) => lastState.current = reducer(state, action) | |
const [state, dispatchOriginal] = useReducer( | |
enhancedReducer, | |
initialState, | |
initializer | |
); | |
const store = useRef({ | |
getState() { | |
return lastState.current; | |
}, | |
dispatch(action) { | |
return dispatchInternal.current(action); | |
}, | |
}); | |
var dispatchInternal = useRef( | |
middleware | |
.reverse() | |
.map((m) => m(store.current)) | |
.reduce((d, m) => m(d), dispatchOriginal) | |
); | |
return [state, store.current.dispatch]; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment