DEV Community

FatimaZahra.Dev
FatimaZahra.Dev

Posted on

How to Create a Dynamic Shopping Cart Total with React useMemo:

Recalculating a shopping cart total on every single page re-render can drastically slow down a React application as the cart grows or as the user interacts with other UI elements. If your component re-renders because of a sidebar toggle or a theme switch, React will completely rebuild that array calculation from scratch, wasting valuable processing power.

The Solution
By using the useMemo hook, we can tell React to cache (or memoize) the computed total value. The application will only recalculate the total price when the actual items inside the cart change, keeping your e-commerce frontend incredibly fast and responsive.

JavaScript
import React, { useState, useMemo } from 'react';

const ShoppingCart = () => {
// Sample cart state containing items from our e-commerce catalog
const [cart, setCart] = useState([
{ id: 1, name: 'Premium Blue Hoodie', price: 45, quantity: 1 },
{ id: 2, name: 'Dark Green Minimalist Watch', price: 120, quantity: 1 },
]);

// useMemo ensures this calculation only runs when the 'cart' array changes
const cartTotal = useMemo(() => {
console.log('Calculating total...'); // This runs only when items change!
return cart.reduce((total, item) => total + (item.price * item.quantity), 0);
}, [cart]);

return (


Your Shopping Cart


    {cart.map(item => (
  • {item.name} Price: ${item.price} | Qty: {item.quantity}
  • ))}



Total Price: ${cartTotal}



);
};

export default ShoppingCart;
How It Works Under the Hood
The Array Reduce Method: Inside the hook, cart.reduce() loops through our items, multiplies each price by its quantity, and adds them up to create a single, clean total number.

The Dependency Array: The [cart] at the very bottom is the critical trigger. It acts as a guard, telling React to completely skip this calculation on incoming re-renders unless the cart data itself is modified.

Performance Optimization: By caching the result, if a user clicks other buttons on your e-commerce page that trigger re-renders, React instantly grabs the saved number instead of looping through the array again.

Cleaner UI Performance: This simple hook prevents layout lag, ensuring that your shopping cart remains seamless and ultra-fast even when handling hundreds of products.

Top comments (0)