In useReducer, is it better to dispatch multiple actions separately for each state field or use a single action to update multiple fields at once?

In a React 17 useReducer setup, is it better to dispatch multiple actions separately, each updating a single state field, or to use a single action that updates multiple fields at once? For example, should I do this

const [state, dispatch] = useReducer(reducer, initialState);

if (data) {
  dispatch({ type: 'updateFieldA', payload: valueA });
  dispatch({ type: 'updateFieldB', payload: valueB });
  dispatch({ type: 'updateFieldC', payload: valueC });
}

// OR

if (data) {
  dispatch({
    type: 'updateAll',
    payload: { fieldA: valueA, fieldB: valueB, fieldC: valueC },
  });
}

I tried dispatching multiple actions separately and also using a single action to update multiple fields. I expected the single action approach to be more performant by reducing re-renders, but I want to confirm the best practice.

Upvotes: -1

Views: 51

Answers (1)

WeDoTheBest4You
WeDoTheBest4You

Reputation: 1954

Each action describes a single user interaction, even if that leads to multiple changes in the data.

As you rightly thought in line with the React team, the following may be the preferred way.

 dispatch({
    type: 'updateAll',
    payload: { fieldA: valueA, fieldB: valueB, fieldC: valueC },
  });

This section may help to reinforce your understanding.

Upvotes: 1

Related Questions