React useReducer Hook: Architecture & State Reducer Pattern

While useState is ideal for simple independent values (like a single boolean toggle or text input), managing complex state objects with multiple interrelated fields can quickly result in scattered, messy state updates. The useReducer hook organizes state transitions into a single predictable dispatcher loop inspired by Redux.

React useReducer Unidirectional Data Flow Diagram

Figure 8: Unidirectional useReducer Cycle: UI Dispatches Action ➔ Reducer Computes New State ➔ UI Re-renders.

Full Shopping Cart Example with useReducer

import React, { useReducer } from 'react';

// 1. Initial State
const initialCartState = {
  items: [],
  totalPrice: 0
};

// 2. Pure Reducer Function: (state, action) => nextState
function cartReducer(state, action) {
  switch (action.type) {
    case 'ADD_ITEM': {
      const updatedItems = [...state.items, action.payload];
      return {
        items: updatedItems,
        totalPrice: updatedItems.reduce((sum, item) => sum + item.price, 0)
      };
    }
    case 'REMOVE_ITEM': {
      const updatedItems = state.items.filter(item => item.id !== action.payload.id);
      return {
        items: updatedItems,
        totalPrice: updatedItems.reduce((sum, item) => sum + item.price, 0)
      };
    }
    case 'CLEAR_CART':
      return initialCartState;
    default:
      throw new Error(`Unhandled action type: ${action.type}`);
  }
}

// 3. Component
function ShoppingCart() {
  const [state, dispatch] = useReducer(cartReducer, initialCartState);

  const handleAddBook = () => {
    const book = { id: Date.now(), title: 'React Mastery Guide', price: 499 };
    dispatch({ type: 'ADD_ITEM', payload: book });
  };

  return (
    <div className="cart-card">
      <h3>Shopping Cart</h3>
      <button onClick={handleAddBook}>Add Book (₹499)</button>
      <button onClick={() => dispatch({ type: 'CLEAR_CART' })} style={{ marginLeft: '10px' }}>
        Empty Cart
      </button>

      <p>Total Items: {state.items.length}</p>
      <h4>Total Price: ₹{state.totalPrice}</h4>
      <ul>
        {state.items.map(item => (
          <li key={item.id}>
            {item.title} - ₹{item.price}
            <button onClick={() => dispatch({ type: 'REMOVE_ITEM', payload: item })}>Remove</button>
          </li>
        ))}
      </ul>
    </div>
  );
}

export default ShoppingCart;

Next Step: Routing with React Router

Now let us step into multi-page single-page applications in React Router v6 Architecture.

Explore Related React JS Tutorials

Accelerate your React mastery by studying these tightly connected core tutorials:

useState vs useReducer →

Choosing between primitive state and action reducers.

Global Reducer State →

Sharing state dispatchers via React Context.

Enterprise Redux Toolkit →

Full-featured enterprise state management architecture.

Share Share on Facebook Share on Twitter Share on LinkedIn Pin on Pinterest Share on Stumbleupon Share on Tumblr Share on Reddit Share on Diggit

You may also like this!