Reputation: 1
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
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