Search code examples
reactjsreducersuse-reducer

What is a better approach to stack multiple actions in reducer per render (React, useReducer)?


What is the best approach to using reduce logic from multiple actions per render? This example shows a basic example of my current solution (creating a new action that combines the logic), but there must be a better way.

The basic example:

I am using useReducer from React, not Redux

const [state, dispatch] = useReducer(reducer, {v1: 0, v2: 0});

Basic reducer that uses a new action that stacks the logic of the first two actions:

function reducer(state, action) {
  const { type, payload: {v1, v2} } = action;
  switch (type) {
    case SET_V1:
      return {...state, v1: setV1(v1)};
    case SET_V2:
      return {...state, v2: setV2(v2)};
    case SET_V1_AND_V2:
      return {...state, v1: setV1(v1), v2: setV2(v2)};
  }
}

Reduce logic delegated to functions to standardise logic:

const setV1 = (v1) => v1;
const setV2 = (v2) => v2;

Thanks for your help


Solution

  • May this could help:

    Related question Using Combine Reducer

    const combineReducers = (slices) => (state, action) =>
      Object.keys(slices).reduce( // use for..in loop, if you prefer it
        (acc, prop) => ({
          ...acc,
          [prop]: slices[prop](acc[prop], action),
        }),
        state
      );