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 + useState patterns
  • 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

  1. Create Routes and Navigation
  2. Data Types and the Product API
  3. Set Up TanStack Query
  4. Display Products with useQuery
  5. Product Detail Page
  6. Cart Reducer
  7. Cart Context and Provider
  8. Wire the Cart into the App
  9. Add to Cart
  10. The Cart Page
  11. Introduction to TanStack Store
  12. Migrate Cart to TanStack Store
  13. Persist Cart to localStorage
  14. Practice Questions