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.
Figure 8: Unidirectional useReducer Cycle: UI Dispatches Action ➔ Reducer Computes New State ➔ UI Re-renders.
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;
Now let us step into multi-page single-page applications in React Router v6 Architecture.
Accelerate your React mastery by studying these tightly connected core tutorials:
Choosing between primitive state and action reducers.
Sharing state dispatchers via React Context.
Full-featured enterprise state management architecture.