Extract the ZIP, open its project folder, and run npm install. Database lessons also need the .env.local setup described below. Checkpoints never contain credentials or node_modules.
1. Understand the problem and the concepts
Why we need this feature
The catalog describes products; the cart describes a shopper’s choices. Combining these two kinds of data would duplicate product information and make updates difficult. Begin with the smallest useful cart: an array of product IDs and quantities.
Start with one interactive component. Each cart line stores a product ID and quantity; the product catalog supplies names and prices. Avoid storing a second total that can become inconsistent.
Adding a product already in the cart increments its quantity. Quantity zero removes it. This first version resets on navigation or refresh; the next lessons address sharing and persistence.
Choose a small state model
A CartLine contains productId and quantity. It does not copy the product name, description or formatted price. Those values already belong to the catalog. When rendering, the component looks up the product by ID and joins that information with the chosen quantity.
lines is React state owned by this cart-page instance. An empty array represents an empty cart. After an update, React renders the same component again using the new array. The ordinary local variable total is recomputed during that render; it is not a second state variable.
Walk through an immutable update
changeQuantity removes the previous line with that product ID into a new others array. If the requested quantity is zero or less, it returns others and the item is removed. Otherwise it appends one replacement line with an integer quantity capped at ten.
The setter uses setLines(old => ...). The callback receives the pending state to update, which avoids relying on a captured older array when updates are queued. Calling push on the existing array would mutate an object React is already using instead of producing a clear next value.
Derive a total rather than synchronizing two states
reduce starts at zero and adds the unit price multiplied by the quantity for each line. With two notebooks and one pen set, the arithmetic is 24900 × 2 + 9900 × 1 = 59700 paise. money converts that result to ₹597.00.
If total were stored separately, every add, remove and quantity change would need to update both lines and total correctly. Deriving it from lines removes that coordination problem. The zero-price fallback avoids a crash when a product is missing; later checkout must reject unavailable products rather than treat them as free.
2. Follow the execution flow
Read this sequence before the source. Identify the input, the component or function that handles it, and the result the learner sees.
1
Clicking Add notebook calls the state setter.
2
The updater reads the old quantity and passes the next quantity to changeQuantity.
3
A new line array becomes the next React state.
4
The component renders the line and recomputes the total from the new state.
Follow three cart operations
Start with []. Add notebook: the old quantity defaults to 0, then becomes 1.
Add notebook again: the matching line supplies quantity 1, then changeQuantity replaces it with quantity 2.
Add pen set: the notebook line stays and a p3 line with quantity 1 is appended. Total is ₹597.00.
Remove notebook: its replacement quantity is 0, so only p3 remains. Total becomes ₹99.00.
3. Build it, one file at a time
Add the shared cart types and the client page below.
Open /cart and add the same product twice.
Read changeQuantity and explain why it returns a new array.
The paths below are relative to your practice project. Each block is the complete file at this checkpoint. Read its responsibility first, type or copy the code, then use the walkthrough to explain the important statements.
lib/cart.ts
This contains the cart line shape and a pure quantity transformation reused by cart state owners.
filter creates a new array without the target product’s previous line. The original array remains unchanged.
A nonpositive quantity returns that array, removing the item. Otherwise a replacement line is appended with an integer quantity capped at ten.
This function has no React hook and performs no persistence. Its caller decides when to store the returned array in state. Server checkout still validates input independently.
app/cart/page.tsx
This renders cart choices and derives their display values from the catalog.
useState owns this page’s array. Its Add buttons use functional updates so repeated choices increment one line.
Each line looks up its product by ID and multiplies its unit price by quantity. reduce adds those line amounts into the displayed total.
Quantity and remove controls request a new array rather than mutating existing state. Missing products have a fallback label; checkout later rejects unavailable choices.
4. Run it and check your result
Adding one notebook twice gives quantity 2 and ₹498.00.
Removing the last line shows the empty-cart message.
5. Predict, change and observe
Add two products, refresh the browser, and compare the result with a normal rerender after clicking Add.
Compare your prediction with the expected result
What you should observe
Clicking preserves earlier cart choices, but a full refresh starts with an empty cart.
Why it happens
State survives renders of the same mounted component. It does not automatically survive a new page load or move into persistent storage.
6. Troubleshoot with evidence
A common mistake
Calling lines.push() changes existing state. Use the functional state setter and return a new array.
Adding an item creates multiple separate lines for the same product.
Likely cause: The code appends blindly instead of finding and replacing a matching line.
Check and correct: Derive the existing quantity by product ID and use changeQuantity to keep one line per product.
The cart changes but the total is stale.
Likely cause: The total was stored or updated separately.
Check and correct: Calculate it from the current lines on each render.
7. Practice and explain it back
Your independent task
Add an Increase button and show why the quantity cannot exceed ten.
Attempt these questions before opening the explanations. Use the source above to justify your answer.
What is the difference between a product and a cart line?
The product holds catalog facts. A cart line records a particular product selection and quantity.
Why use a functional setter?
It calculates the next value from React’s pending previous value, which is safer when multiple state updates can be queued.