Skip to content

Instantly share code, notes, and snippets.

@alpox
Created November 27, 2020 20:59
Show Gist options
  • Save alpox/4de7d6cbefdd535111d69b766fa9f85a to your computer and use it in GitHub Desktop.
Save alpox/4de7d6cbefdd535111d69b766fa9f85a to your computer and use it in GitHub Desktop.
Hook: useReduxReducer
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