How do you pass extra data along with an action when using useReducer?
Short answer
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.
Advertisement
AModel answer
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.
Likely follow-ups
- Is there a required naming convention for the extra data included in an action?
- How would you dispatch multiple different pieces of data together in a single action?
Related topics