Set your Publisher ID in src/config/ads.ts to display live ads.
useReducer: Managing Complex State Transitions
The reducer function, dispatching actions, and scalable state logic
When component state involves multiple sub-values or when the next state depends on the previous one, useReducer provides predictable Redux-style action dispatching.
The Reducer Pattern in React
Reducer Function: (state, action) => nextState. A pure function calculating the new state based on action type and payload.
dispatch(action): Dispatches an action object (e.g. { type: "ADD_ITEM", payload: item }).
Predictability: All state mutations are centralized inside a single switch statement, making debugging and unit testing effortless.
const initialState = { items: [], total: 0 };
function cartReducer(state, action) {
switch (action.type) {
case 'ADD_ITEM':
return {
...state,
items: [...state.items, action.payload],
total: state.total + action.payload.price
};
case 'CLEAR_CART':
return initialState;
default:
return state;
}
}
function Cart() {
const [state, dispatch] = React.useReducer(cartReducer, initialState);
return (
<div>
<p>Total items: {state.items.length}, Sum: ${state.total}</p>
<button onClick={() => dispatch({ type: 'ADD_ITEM', payload: { id: 1, price: 49.99 } })}>
Add Course ($49.99)
</button>
</div>
);
}Set your Publisher ID in src/config/ads.ts to display live ads.
Test Yourself With Exercise
What kind of function must a React reducer passed to `useReducer` be?