React
Add product UI
Write a panel that lists products and adds them to the cart.
Add-to-cart UI
The final lesson writes the ProductCard and CartSummary components. The product card dispatches ADD; the summary reads total from state.
ProductCard: gets dispatch with const dispatch = useContext(CartDispatchContext);. On button click, dispatch({ '{ type: "ADD", payload: product }' }).
CartSummary: reads state with const state = useContext(CartStateContext);. Shows state.total and state.items.length. This is where the three lessons merge.
Cart summary
CartSummary reads state with useContext(CartStateContext). state.items.length gives item count, state.total gives total. It prints both.
On every state change (ADD, REMOVE, CLEAR), CartSummary re-renders automatically. ProductCard using CartDispatchContext isn't affected by state changes.
This is where the power of two contexts shows: components that only read or only write don't render needlessly. This gives a smooth experience in big cart apps.
Exercise Write ProductCard
Complete the skeleton. Write a ProductCard component. Take ({ '{ product }' }). Get dispatch with const dispatch = useContext(CartDispatchContext);. Return <div><h3>{ '{ product.name }' }</h3><p>{ '{ product.price }' } TL</p><button onClick={ '{ () => dispatch({ '{ type: "ADD", payload: product }' }) }' }>Add</button></div>. Export it.
Show example solution
import { useContext } from "react";
function ProductCard({ product }) {
const dispatch = useContext(CartDispatchContext);
return (
<div>
<h3>{product.name}</h3>
<p>{product.price} TL</p>
<button onClick={() => dispatch({ type: "ADD", payload: product })}>Add</button>
</div>
);
}
export default ProductCard;
Test yourself
-
Which context does ProductCard use?
- CartDispatchContext
- CartStateContext
- ThemeContext
- UserContext
Show answer
CartDispatchContext — ProductCard uses CartDispatchContext.
-
ADD action
To add a product, dispatch({ type: "ADD", payload: product }); product goes into ____.
Show answer
To add a product, dispatch({ type: "ADD", payload: product }); product goes into payload.
-
Match the add-to-cart flow
- ProductCard
- ADD
- dispatch
- cartReducer
- CartSummary
- state.total
- CartProvider
- wraps
Next lesson: What is useMemo?