CodeBlanks Logo Icon CodeBlanks

Project: Cart management

Review the goal and steps of the cart management project.

Project: Cart management

In this project we'll build a cart management system step by step. Three lessons: cart reducer, cart context, and add-to-cart UI. Each lesson builds on the previous.

State is managed with useReducer: { '{ items: [], total: 0 }' }. Actions: ADD, REMOVE, CLEAR. The reducer handles these.

Context distributes the reducer result to all components. This keeps the global cart state clean and testable. After three lessons you get a real e-commerce flow.

Three-step structure

The first lesson writes the cartReducer function: handles ADD, REMOVE, CLEAR actions via switch. Each case returns a new state object.

The second lesson writes the CartProvider component: calls useReducer, wraps with two contexts. State and dispatch are in separate contexts; so components using only dispatch don't render needlessly.

The third lesson adds a product list and cart summary. Product cards dispatch ADD; the summary reads items and total from state. This is where the three lessons merge.

Practice Cart skeleton

Complete the skeleton. Write a CartApp component. Call useReducer(cartReducer, { '{ items: [], total: 0 }' }); destructure as [state, dispatch]. Return <main><h1>Cart</h1><p>{ '{ state.total }' } TL</p></main>. Export it.

Starter code

App.jsx
import { useReducer } from "react";

// Write the CartApp component here

Sample solution

App.jsx
import { useReducer } from "react";

function CartApp() {
  const [state, dispatch] = useReducer(cartReducer, { items: [], total: 0 });
  return (
    <main>
      <h1>Cart</h1>
      <p>{state.total} TL</p>
    </main>
  );
}

export default CartApp;

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Which is NOT in the cart state?

  • items
  • color Correct answer
  • total
  • ADD

Explanation: color is not in the state.

2 Cart action

Question
To add a product to the cart, dispatch ____.
Answer
To add a product to the cart, dispatch ADD.

Explanation: ADD adds a product.

3 Match the cart steps

Term Meaning
cartReducer switch
CartProvider two contexts
ProductCard ADD
CartSummary total

All lessons in Intermediate