


Lightweight, no dependency library for redux reducers
npm install --save redux-reducer-utils
Or
yarn add redux-reducer-utils
createReducer provides more declarative way to describe redux reducer
Just callcreateReducer with initial state as argument and theninvoke chainwhen to register actions handlers, finally calltoFunction to build reducer
import{createReducer}from'redux-reducer-utils';constinitialState={a:1,b:2,c:3,d:4,};constreducer=createReducer(initialState).when(ACTION_TYPE_1,(state,action)=>({ ...state,a:state.a+action.payload,})).when(ACTION_TYPE_4,(state,action)=>({ ...state,c:state.c+action.payload,})).toFunction();Here comparison classic reducer description withcreateReducer way
constACTION_TYPE_1='ACTION_TYPE_1';constACTION_TYPE_2='ACTION_TYPE_2';constACTION_TYPE_3='ACTION_TYPE_3';constACTION_TYPE_4='ACTION_TYPE_4';constinitialState={a:1,b:2,c:3,d:4,};constclassicReducer=(state=initialState,action)=>{switch(action.type){caseACTION_TYPE_1:return{ ...state,a:state.a+action.payload,};caseACTION_TYPE_2:caseACTION_TYPE_3:return{ ...state,b:state.b+action.payload,};caseACTION_TYPE_4:return{ ...state,c:state.c+action.payload,};default:returnstate;}};constwithCreateReducer=createReducer(initialState).when(ACTION_TYPE_1,(state,action)=>({ ...state,a:state.a+action.payload,}))//if you need the same handler for two or more actions types, just put array to first argument.when([ACTION_TYPE_2,ACTION_TYPE_3],(state,action)=>({ ...state,b:state.b+action.payload,})).when(ACTION_TYPE_4,(state,action)=>({ ...state,c:state.c+action.payload,})).toFunction();composeReducers This function can help with reducers horizontal scaling
Everyi reducer has access toi-1 state
import{composeReducers}from'redux-reducer-utils';constSOME_ACTION='SOME_ACTION';constinitialStateFirst={a:1,b:2,};constinitialStateSecond={c:3,d:3,};constfirstReducer=(state=initialStateFirst,action)=>{//...some actions handlers};constsecondReducer=(state=initialStateSecond,action)=>{//...here you have access to state from firstReducerswitch(action.type){caseSOME_ACTION:return{ ...state,a:state.a+action.payload,};default:returnstate;}};exportconstcomposedReducer=composeReducers(firstReducer,secondReducer,/*...any number of reducers*/);