ADVERTISEMENT
Google AdSense Slot (headerLeaderboard)

Set your Publisher ID in src/config/ads.ts to display live ads.

React.js Tutorial• 7 min read

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.

Shopping Cart with useReducer
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>
  );
}
ADVERTISEMENT
Google AdSense Slot (inContentBanner)

Set your Publisher ID in src/config/ads.ts to display live ads.

Test Yourself With Exercise

+15 XP

What kind of function must a React reducer passed to `useReducer` be?