UNPKG

use-middleware-reducer

Version:

An efficient react hook to benefit from the huge middleware ecosystem of redux

31 lines (28 loc) 1.32 kB
import { useMemo, useRef, useState } from 'react'; var useMiddlewareReducer = function (reducer, initialState, middlewares) { if (middlewares === void 0) { middlewares = []; } var _a = useState(initialState), state = _a[0], setState = _a[1]; var stateRef = useRef(state); var dispatch = useMemo(function () { var dispatch = function () { throw new Error("Dispatching while constructing your middleware is not allowed. " + "Other middleware would not be applied to this dispatch."); }; var middlewareAPI = { getState: function () { return stateRef.current; }, dispatch: function (action) { return dispatch(action); } }; var localDispatch = function (action) { stateRef.current = reducer(stateRef.current, action); setState(stateRef.current); }; dispatch = middlewares .map(function (middleware) { return middleware(middlewareAPI); }) .reduceRight(function (acc, middleware) { return middleware(acc); }, localDispatch); return dispatch; // eslint-disable-next-line react-hooks/exhaustive-deps }, []); return [state, dispatch]; }; export { useMiddlewareReducer }; export default useMiddlewareReducer;