ReviseAlgo Logo

Projects

Ecommerce

Master building a React E-commerce store, covering product catalog filters, search functions, shopping cart states, and pricing math.

Last Updated: July 15, 2026 12 min read

1. Learning Objectives

In this project, you will build an interactive E-commerce Product Catalog and Shopping Cart. By the end of this project, you will be able to:

  • Implement multi-criteria product filtering (by category, price range, and search terms).
  • Manage shopping cart items using an array of objects containing product detail details and quantity keys.
  • Perform shopping cart actions (adding items, updating quantities, and removing items) immutably in state.
  • Calculate subtotals, tax, and order totals dynamically using derived state.
  • Coordinate parent layout states with slide-out cart drawers.

2. Overview

An **E-commerce Store** combines catalog filtering with shopping cart state management. It covers state declarations, object arrays, derived states (calculating totals dynamically), and event handlers for updating quantities and deleting items.

3. Why This Project Matters

E-commerce patterns are foundational to modern web applications:

  • Derived State Calculations: You learn why you shouldn't duplicate cart pricing metrics in state, instead deriving values like totals dynamically from the items array during rendering.
  • Complex Object Updates: You learn how to update specific nested properties (like incrementing a single item's quantity) immutably inside state arrays.

4. Real-World Analogy

Think of an E-commerce application like **shopping with a checklist and physical cart**:

  • Catalog Filters: Walking directly to the aisle marked "Electronics" and ignoring the other aisles (filtering search arrays).
  • The Cart Array: Placing items in your cart. If you pick up another box of cookies, you don't list it as a separate item; you write "x2" next to the cookie checkbox on your list (updating item quantities immutably).
  • Checkout Calculations: The cashier totals up your items at the checkout counter, adding tax and discounts dynamically. The cashier doesn't keep a separate tally for every item you add; they calculate the final price once based on what's in the cart (derived state calculation).

5. Core Concepts

Below is a comparison of monolithic state and derived state calculations:

Property Duplicated State Pattern (Anti-pattern) Derived State Pattern (Recommended)
Implementation Declaring separate state variables for subtotal and tax. Calculating subtotals and tax dynamically during render: const subtotal = items.reduce(...).
Synchronization Risk High. Forgetting to update subtotals when adding or removing items leads to incorrect pricing displays. None. Derived metrics are calculated fresh whenever the items array updates.
Memory/State Size High; requires updating multiple state setters on every change. Low; requires storing only the raw items array in state.

6. Syntax & API Reference

This example shows how to add items and update quantities immutably in the cart state:

7. Visual Diagram

This diagram displays how product actions update the cart state and trigger pricing recalculations:

8. Live Example — Full Working Code

Below is a complete HTML page demonstrating a working product catalog and shopping cart system:

What just happened? Adding products maps and updates the cart state array immutably. Subcomponent updates and quantity toggles re-render the application, recalculating the derived totals dynamically from the cart items array, preventing state synchronization errors.

9. Interactive Playground

Try It Yourself Challenges:

  1. Modify the quantity changer code so that clicking the decrement button (-) when the quantity is 1 automatically removes the item from the cart.
  2. Add a 10% coupon input field that subtracts a discount from the final subtotal when a valid code (e.g. "SAVE10") is applied.

10. Common Mistakes

Mistake Why it happens Wrong Correct
Storing derived layout values in state Declaring state variables for values that can be calculated from existing state (like subtotal or cartCount) increases code complexity and risks states getting out of sync. Declaring const [subtotal, setSubtotal] = useState(0) and updating it manually inside effects. Calculate the subtotal dynamically from the cart state array during rendering: const subtotal = cart.reduce(...).
Duplicate entries when adding existing products to the cart Appending a product to the cart array without checking if it already exists creates duplicate rows in the cart, instead of incrementing the existing product's quantity. setCart([...cart, product]) (ignores duplicate check) Check if the item exists first. If it does, map the array and increment its quantity. Otherwise, append the new product to the array.

11. Best Practices

  • Derive cart calculations: Calculate metrics like subtotals, tax, and item counts dynamically from the cart items state array during rendering.
  • Check for duplicates: Check if a product already exists in the cart before adding it, incrementing the quantity if it does.
  • Update nested properties safely: Map over the cart state array and create shallow copies of objects when updating properties like item quantities.
  • Add validation inside handlers: Validate quantity changes in your handlers to prevent items from having negative or zero quantities.

12. Browser Compatibility/Requirements

This project runs on all modern browsers supporting standard JavaScript array methods.

13. Interview Questions

Q1: What is derived state? Why should we calculate the cart subtotal dynamically instead of storing it in a state variable?

Answer: Derived state is state that can be calculated from existing state values. We calculate the cart subtotal dynamically (using `reduce`) during rendering because it is derived directly from the `cart` state array. Storing the subtotal in a separate state variable requires updating it manually whenever the cart updates, which increases code complexity and risks states getting out of sync.

Q2: How do you update a nested property (like an item's quantity) inside an array in React state without mutating it?

Answer: Map over the state array to find the target item, and return a new array with a shallow copy of the updated object: `setCart(prev => prev.map(item => item.id === targetId ? { ...item, quantity: item.quantity + 1 } : item))`

14. Debugging Exercise

Identify why incrementing an item's quantity also changes that item's quantity in the main product catalog database:

View Solution

Diagnosis: The addToCart function adds a property to the catalog product object directly (product.quantity = 1) and appends it to the cart. Since objects are passed by reference, this mutates the original object in the product catalog database directly.

Fix: Create a shallow copy of the product object when adding it to the cart to avoid mutating the original catalog object:

15. Practice Exercises

Exercise 1: Create a categorizer selector filter

Extend the E-commerce store by adding a category select dropdown. When a category is selected, filter the product list dynamically to display only items matching that category.

16. Scenario-Based Challenge

The Multi-Warehouse Stock Availability constraint:

You are designing a cart drawer for a system where products have inventory limits across warehouses. Users cannot add items to their cart past the available stock limit. Describe how you would update the add-to-cart handler to check inventory limits before updating the cart.

17. Quick Quiz

Q1: Which method should be used to calculate a single summary total (like the cart subtotal) from an array of objects?

A) map()

B) reduce()

C) find()

Answer: B — The reduce() method executes a reducer function on each element of the array, returning a single accumulated value.

18. Summary & Key Takeaways

  • Calculate derived values (like totals or counts) dynamically during rendering instead of storing them in state.
  • Create shallow copies of objects when updating properties like item quantities inside state arrays.
  • Check if a product already exists in the cart before adding it to prevent duplicate entries.
  • Always use non-mutating methods to update array states in React.

19. Cheat Sheet

Shopping Cart Operation Syntax Example
cart.find(t => t.id === p.id) Checks if a product already exists in the cart.
cart.reduce((s, t) => s + (t.p * t.q), 0) Accumulates subtotals dynamically from the cart items array.
cart.map(t => t.id === id ? { ...t, q: t.q + 1 } : t) Increments the quantity of a specific item immutably.
---