React › useReducer & Complex State Logic
How do you pass extra data along with an action when using useReducer?
IntermediateAnswer
An action object can include any additional properties beyond just its type, commonly called a payload, letting the reducer know exactly what data it needs to correctly compute the new state for that specific action.
function reducer(state, action) {
switch (action.type) {
case 'addItem':
return { items: [...state.items, action.payload] };
default:
return state;
}
}
dispatch({ type: 'addItem', payload: { id: 1, name: 'Apple' } });Real-world example A shopping cart reducer receives the specific item being added as a payload inside the dispatched action, letting it correctly add exactly that item to the existing list of cart items.