Shopping Cart App
In this tutorial, you will build a shopping cart. It is an eStore where users browse products from a remote API, view product details, and manage a cart. Along the way, you will learn three important concepts:
- TanStack Query: fetching, caching, and displaying server data without manual
useEffect+useStatepatterns - React Context: sharing state (the cart) across multiple components without prop drilling
- TanStack Store: a lightweight, framework-agnostic alternative to Context for global state management
Getting Started
Go to the shopping-cart repository and click “Use this template” → “Create a new repository” to create your own copy.
Clone your repository to your computer:
git clone <your-repo-url> shopping-cart
cd shopping-cart
code .
The template is a TypeScript React app scaffolded with Vite. It includes Prettier, Tailwind CSS, shadcn/ui, and TanStack Router (all pre-configured from the previous chapter). Install dependencies and start the dev server:
pnpm install
pnpm dev
You should see a page with “eStore” in the header.
If you get stuck at any point, you can view the complete solution on the master branch of the original repository.
If your repository name is different from shopping-cart, make sure you also update the GitHub Pages base in vite.config.ts and the router basepath in src/main.tsx later in the chapter so they match your repository name.
Learning Outcomes
- Fetch, cache, and display server data with TanStack Query, including loading and error states
- Define TypeScript types for API and application data, and route between pages with route params
- Model state changes with a reducer and share that state across components with React Context
- Explain the limitations of Context and migrate shared state to TanStack Store for more efficient updates
- Persist application state to localStorage so it survives a page refresh
- Build a working shopping cart feature end to end: browsing products, viewing product details, and managing cart items
Sections
- Create Routes and Navigation
- Data Types and the Product API
- Set Up TanStack Query
- Display Products with useQuery
- Product Detail Page
- Cart Reducer
- Cart Context and Provider
- Wire the Cart into the App
- Add to Cart
- The Cart Page
- Introduction to TanStack Store
- Migrate Cart to TanStack Store
- Persist Cart to localStorage
- Practice Questions