Appearance
6.4.15 — Capstone: The Whole Shop, Piece by Piece
You now know nine tools. Each page taught one of them alone. A real app uses them together, and the hard part is not any single tool. It is knowing which tool owns which piece of data, so that nothing is stored twice and nothing is forgotten.
This page builds one small shop that uses all of them. A customer searches for products, opens one, adds it to a cart, fills a checkout form, and sees a thank-you page. Every line of code here was type-checked, and the whole flow was run end to end in a test browser. When you read a file, you will see the same ideas you have already met, now working in one place.
1. Who owns what
Before writing code, list every piece of data in the app and decide its owner. This is the skill that separates a tidy app from a tangled one. The rule from page 6.4.6: one owner per piece of data, chosen by where the data really lives.
| Data | Where it really lives | Owner | Why |
|---|---|---|---|
| The list of products, one product's details | The server | TanStack Query | It is a copy of server data. It needs caching and refreshing |
| Which page, which product id, the search text, the sort | The address bar | TanStack Router | The user can share it, bookmark it, and press Back |
| The items in the cart | The browser | Zustand | It exists only here until the order is placed. Many components read it |
| What the user is typing at checkout, the errors | The form | React Hook Form | Cheap on re-renders, handles errors and submitting |
| Whether the shape of data is right | Nowhere, it is a rule | Zod schemas | One description, used at every edge |
| A drawer open, a hover | The component | useState | Nobody else cares |
Notice what is not in the table: the products are not in Zustand, the search text is not in useState, and the checkout values are not in Redux or Context. Each of those would be a second copy that can go out of date.
2. The folders
text
src/
schemas/
product.ts Zod: what a product from the server looks like
checkout.ts Zod: what a valid checkout form looks like
api/
client.ts getValidated and sendValidated (fetch + check with Zod)
products.ts query options for products
orders.ts the function that places an order
fakeServer.ts a stand-in server, so this example runs with no backend
stores/
cartStore.ts Zustand: the cart
routes/ TanStack Router: one file per page
__root.tsx header and shared layout
index.tsx /
cart.tsx /cart
checkout.tsx /checkout
products/index.tsx /products
products/$productId.tsx
thanks/$orderId.tsx
router.tsx
main.tsxThe folders follow the kind of work: schemas, talking to the server, client state, pages. Pages are the only place where the pieces meet.
3. The schemas: the shape of the data, written once
ts
// src/schemas/product.ts
import { z } from 'zod'
export const productSchema = z.object({
id: z.string(),
name: z.string().min(1),
priceCents: z.int().nonnegative(),
inStock: z.boolean(),
})
export type Product = z.infer<typeof productSchema>ts
// src/schemas/checkout.ts
import { z } from 'zod'
export const checkoutSchema = z.object({
name: z.string().trim().min(1, 'Please enter your name'),
email: z.email('Enter a valid email'),
country: z.enum(['PT', 'DE']),
giftWrap: z.boolean(),
note: z.string().max(100, 'Keep the note under 100 characters'),
})
export type CheckoutValues = z.infer<typeof checkoutSchema>These two files are the center of the app. Page 6.4.13 explained every line. Everything else will import from here.
4. Talking to the server
The client: fetch, then check
ts
// src/api/client.ts
import { z } from 'zod'
async function readJson<S extends z.ZodType>(res: Response, schema: S): Promise<z.infer<S>> {
if (!res.ok) throw new Error(`The server answered ${res.status}`) // (1)
const parsed = schema.safeParse(await res.json()) // (2)
if (!parsed.success) {
const first = parsed.error.issues[0]
throw new Error(`Unexpected data from the server at "${first?.path.join('.')}": ${first?.message}`)
}
return parsed.data // (3)
}
export async function getValidated<S extends z.ZodType>(
url: string,
schema: S,
signal?: AbortSignal,
): Promise<z.infer<S>> {
return readJson(await fetch(url, { signal }), schema)
}
export async function sendValidated<S extends z.ZodType>(
url: string,
body: unknown,
schema: S,
): Promise<z.infer<S>> {
const res = await fetch(url, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(body),
})
return readJson(res, schema)
}fetchdoes not fail on 404 or 500, so we checkres.okonce, here. (Page 6.4.3.)- The reply is checked against a schema. Anything that does not match becomes an error with the path of the bad field. (Page 6.4.13.)
- Only checked data leaves. Everything after this point has a trustworthy type, so we never need
as.
Query options: one place for each key and function
ts
// src/api/products.ts
import { queryOptions } from '@tanstack/react-query'
import { z } from 'zod'
import { getValidated } from './client'
import { productSchema } from '../schemas/product'
export const productKeys = {
all: ['products'] as const,
list: (q: string) => [...productKeys.all, 'list', { q }] as const,
detail: (id: string) => [...productKeys.all, 'detail', id] as const,
}
export const productListOptions = (q: string) =>
queryOptions({
queryKey: productKeys.list(q),
queryFn: ({ signal }) =>
getValidated(`/api/products?q=${encodeURIComponent(q)}`, z.array(productSchema), signal),
staleTime: 30_000,
})
export const productDetailOptions = (id: string) =>
queryOptions({
queryKey: productKeys.detail(id),
queryFn: ({ signal }) => getValidated(`/api/products/${id}`, productSchema, signal),
staleTime: 30_000,
})This is page 6.4.10 in two small functions. The key holds everything the function uses (q, id). Because the function uses getValidated, the type of data is worked out from the schema, with no type written by hand.
Placing an order
ts
// src/api/orders.ts
import { z } from 'zod'
import { sendValidated } from './client'
import type { CheckoutValues } from '../schemas/checkout'
const orderReceiptSchema = z.object({ orderId: z.string() })
export type OrderLine = { productId: string; quantity: number }
export function placeOrder(customer: CheckoutValues, lines: OrderLine[]) {
return sendValidated('/api/orders', { customer, lines }, orderReceiptSchema)
}A pretend server
So that you can run the example with no backend, here is a tiny in-memory server that looks like fetch. In a real project you delete this file and the one line in main.tsx that installs it.
ts
// src/api/fakeServer.ts
import type { Product } from '../schemas/product'
const products: Product[] = [
{ id: 'p1', name: 'Red mug', priceCents: 1999, inStock: true },
{ id: 'p2', name: 'Desk lamp', priceCents: 4500, inStock: true },
{ id: 'p3', name: 'Notebook', priceCents: 650, inStock: false },
]
let nextOrder = 1001
const json = (body: unknown, status = 200) =>
new Response(JSON.stringify(body), { status, headers: { 'Content-Type': 'application/json' } })
export async function fakeFetch(input: RequestInfo | URL, init?: RequestInit): Promise<Response> {
const url = new URL(String(input), 'http://shop.test')
await new Promise((resolve) => setTimeout(resolve, 30)) // pretend the network is slow
if (url.pathname === '/api/products') {
const q = (url.searchParams.get('q') ?? '').toLowerCase()
return json(products.filter((p) => p.name.toLowerCase().includes(q)))
}
const detail = url.pathname.match(/^\/api\/products\/(\w+)$/)
if (detail) {
const product = products.find((p) => p.id === detail[1])
return product ? json(product) : json({ message: 'No such product' }, 404)
}
if (url.pathname === '/api/orders' && init?.method === 'POST') {
return json({ orderId: `o-${nextOrder++}` }, 201)
}
return json({ message: 'Not found' }, 404)
}5. The cart: Zustand
ts
// src/stores/cartStore.ts
import { create } from 'zustand'
import { persist } from 'zustand/middleware'
export type CartItem = { productId: string; name: string; priceCents: number; quantity: number }
type CartStore = {
items: CartItem[]
addItem: (product: Omit<CartItem, 'quantity'>) => void
removeItem: (productId: string) => void
clear: () => void
}
export const useCartStore = create<CartStore>()(
persist(
(set) => ({
items: [],
addItem: (product) =>
set((state) => {
const existing = state.items.find((i) => i.productId === product.productId)
if (existing) {
return {
items: state.items.map((i) =>
i.productId === product.productId ? { ...i, quantity: i.quantity + 1 } : i,
),
}
}
return { items: [...state.items, { ...product, quantity: 1 }] }
}),
removeItem: (productId) =>
set((state) => ({ items: state.items.filter((i) => i.productId !== productId) })),
clear: () => set({ items: [] }),
}),
{ name: 'shop-cart', partialize: (state) => ({ items: state.items }) }, // (1)
),
)
export const selectItemCount = (state: CartStore) =>
state.items.reduce((sum, i) => sum + i.quantity, 0) // (2)
export const selectTotalCents = (state: CartStore) =>
state.items.reduce((sum, i) => sum + i.priceCents * i.quantity, 0)- Page 6.4.8: save only the data, not the functions, so the cart survives a reload. We checked that after adding a product,
localStorageheld{"state":{"items":[...]},"version":0}. - The count and the total are calculated by selectors, not stored. This is the rule from page 6.4.2: store the minimum, calculate the rest.
6. The pages
The root layout
tsx
// src/routes/__root.tsx
import { createRootRouteWithContext, Link, Outlet } from '@tanstack/react-router'
import type { QueryClient } from '@tanstack/react-query'
import { selectItemCount, useCartStore } from '../stores/cartStore'
export const Route = createRootRouteWithContext<{ queryClient: QueryClient }>()({
component: RootLayout,
notFoundComponent: () => <p>Page not found</p>,
})
function RootLayout() {
const itemCount = useCartStore(selectItemCount) // (1)
return (
<>
<header>
<nav>
<Link to="/" activeOptions={{ exact: true }}>Shop</Link>
<Link to="/products">Products</Link>
<Link to="/cart">Cart ({itemCount})</Link>
</nav>
</header>
<main>
<Outlet />
</main>
</>
)
}- The header reads only the count from the cart. When the cart changes, the header re-renders, and components that do not read the cart do not. (Page 6.4.7 and 6.4.8, selectors.)
The product list: URL, cache and loader together
tsx
// src/routes/products/index.tsx
import { createFileRoute, Link, useNavigate } from '@tanstack/react-router'
import { useSuspenseQuery } from '@tanstack/react-query'
import type { FormEvent } from 'react'
import { productListOptions } from '../../api/products'
export const Route = createFileRoute('/products/')({
validateSearch: (search: Record<string, unknown>): { q?: string } => ({ // (1)
q: typeof search.q === 'string' && search.q !== '' ? search.q : undefined,
}),
loaderDeps: ({ search }) => ({ q: search.q ?? '' }), // (2)
loader: ({ context, deps }) => context.queryClient.ensureQueryData(productListOptions(deps.q)), // (3)
component: ProductsPage,
})
function ProductsPage() {
const { q = '' } = Route.useSearch() // (4)
const { data: products } = useSuspenseQuery(productListOptions(q)) // (5)
const navigate = useNavigate({ from: '/products/' })
function handleSearch(e: FormEvent<HTMLFormElement>) {
e.preventDefault()
const text = String(new FormData(e.currentTarget).get('q') ?? '').trim()
navigate({ search: { q: text === '' ? undefined : text } }) // (6)
}
return (
<>
<form onSubmit={handleSearch}>
<input name="q" defaultValue={q} placeholder="Search products" />
<button type="submit">Search</button>
</form>
{products.length === 0 ? (
<p>Nothing matches “{q}”.</p>
) : (
<ul>
{products.map((p) => (
<li key={p.id}>
<Link to="/products/$productId" params={{ productId: p.id }}>{p.name}</Link>
{' '}· ${(p.priceCents / 100).toFixed(2)}
{!p.inStock && ' (sold out)'}
</li>
))}
</ul>
)}
</>
)
}- The search text lives in the URL (page 6.4.12).
validateSearchaccepts only a non-empty string. Anything else becomes "no search". - The loader depends on
q. Whenqchanges, the loader runs again. - The loader asks the Query cache for the products, and waits. If the cache already has fresh data for this key, no request goes out (page 6.4.11).
- The component reads the same
qfrom the URL. useSuspenseQueryreads the same cache entry. The data is already there, because the loader made sure of it, so there is no loading check.productshas the typeProduct[], worked out from the schema throughgetValidated.- A search is a navigation. We change the URL, which changes
q, which runs the loader, which fills the cache, which updates the list. NouseStateis involved, and the page can be shared as/products?q=lamp.
One product, and "Add to cart"
tsx
// src/routes/products/$productId.tsx
import { createFileRoute, Link } from '@tanstack/react-router'
import { useSuspenseQuery } from '@tanstack/react-query'
import { productDetailOptions } from '../../api/products'
import { useCartStore } from '../../stores/cartStore'
export const Route = createFileRoute('/products/$productId')({
loader: ({ context, params }) =>
context.queryClient.ensureQueryData(productDetailOptions(params.productId)),
errorComponent: () => (
<section>
<h1>We could not find that product</h1>
<Link to="/products">Back to all products</Link>
</section>
),
component: ProductPage,
})
function ProductPage() {
const { productId } = Route.useParams()
const { data: product } = useSuspenseQuery(productDetailOptions(productId))
const addItem = useCartStore((state) => state.addItem) // (1)
return (
<article>
<h1>{product.name}</h1>
<p>${(product.priceCents / 100).toFixed(2)}</p>
<button
disabled={!product.inStock}
onClick={() => addItem({ productId: product.id, name: product.name, priceCents: product.priceCents })}
>
{product.inStock ? 'Add to cart' : 'Sold out'}
</button>
</article>
)
}- This component selects only the
addItemfunction, which never changes. So it does not re-render when the cart changes.
If the server answers 404, getValidated throws, the loader fails, and the route's errorComponent is drawn. Nothing else needed.
The cart page
tsx
// src/routes/cart.tsx
import { createFileRoute, Link } from '@tanstack/react-router'
import { selectTotalCents, useCartStore } from '../stores/cartStore'
export const Route = createFileRoute('/cart')({
component: CartPage,
})
function CartPage() {
const items = useCartStore((state) => state.items)
const removeItem = useCartStore((state) => state.removeItem)
const totalCents = useCartStore(selectTotalCents)
if (items.length === 0) {
return (
<section>
<p>Your cart is empty.</p>
<Link to="/products">Browse products</Link>
</section>
)
}
return (
<section>
<ul>
{items.map((item) => (
<li key={item.productId}>
{item.name} × {item.quantity} · ${((item.priceCents * item.quantity) / 100).toFixed(2)}
<button onClick={() => removeItem(item.productId)}>Remove</button>
</li>
))}
</ul>
<p>Total: ${(totalCents / 100).toFixed(2)}</p>
<Link to="/checkout">Go to checkout</Link>
</section>
)
}The checkout: form, schema and mutation together
tsx
// src/routes/checkout.tsx
import { createFileRoute, useNavigate } from '@tanstack/react-router'
import { useMutation } from '@tanstack/react-query'
import { useForm } from 'react-hook-form'
import { zodResolver } from '@hookform/resolvers/zod'
import { checkoutSchema } from '../schemas/checkout'
import type { CheckoutValues } from '../schemas/checkout'
import { placeOrder } from '../api/orders'
import { useCartStore } from '../stores/cartStore'
export const Route = createFileRoute('/checkout')({
component: CheckoutPage,
})
function CheckoutPage() {
const navigate = useNavigate()
const items = useCartStore((state) => state.items)
const clearCart = useCartStore((state) => state.clear)
const { register, handleSubmit, formState: { errors } } = useForm<CheckoutValues>({
resolver: zodResolver(checkoutSchema), // (1)
defaultValues: { name: '', email: '', country: 'PT', giftWrap: false, note: '' },
})
const order = useMutation({
mutationFn: (customer: CheckoutValues) =>
placeOrder(customer, items.map((i) => ({ productId: i.productId, quantity: i.quantity }))), // (2)
onSuccess: ({ orderId }) => {
clearCart() // (3)
navigate({ to: '/thanks/$orderId', params: { orderId } }) // (4)
},
})
if (items.length === 0) return <p>Your cart is empty, so there is nothing to check out.</p>
return (
<form onSubmit={handleSubmit((values) => order.mutate(values))} noValidate> {/* (5) */}
<label>
Name
<input {...register('name')} aria-invalid={errors.name ? true : undefined} />
</label>
{errors.name && <p role="alert">{errors.name.message}</p>}
<label>
Email
<input type="email" {...register('email')} aria-invalid={errors.email ? true : undefined} />
</label>
{errors.email && <p role="alert">{errors.email.message}</p>}
<label>
Country
<select {...register('country')}>
<option value="PT">Portugal</option>
<option value="DE">Germany</option>
</select>
</label>
<label>
<input type="checkbox" {...register('giftWrap')} />
Gift wrap
</label>
<label>
Note
<textarea {...register('note')} />
</label>
{errors.note && <p role="alert">{errors.note.message}</p>}
{order.isError && <p role="alert">We could not place the order: {order.error.message}</p>}
<button type="submit" disabled={order.isPending}>
{order.isPending ? 'Placing order…' : 'Place order'}
</button>
</form>
)
}- The checkout form uses the same schema file that describes valid checkout data everywhere. The form's types come from it (
useForm<CheckoutValues>), and so do its error messages. (Page 6.4.14.) - The mutation turns the cart into the lines the server wants. The cart comes from Zustand. The customer comes from the form. They meet here and nowhere else.
- After success, the cart is emptied. (Page 6.4.11: a mutation changes things, and then you update what depends on it.)
- We move to the thank-you page with a typed
params. A typo in the route name or a missingorderIdwould not compile. handleSubmitruns the checks. Only valid values reachorder.mutate.
The thank-you page
tsx
// src/routes/thanks/$orderId.tsx
import { createFileRoute, Link } from '@tanstack/react-router'
export const Route = createFileRoute('/thanks/$orderId')({
component: ThanksPage,
})
function ThanksPage() {
const { orderId } = Route.useParams()
return (
<section>
<h1>Thank you!</h1>
<p>Your order number is {orderId}.</p>
<Link to="/products">Keep shopping</Link>
</section>
)
}The home page
tsx
// src/routes/index.tsx
import { createFileRoute, Link } from '@tanstack/react-router'
export const Route = createFileRoute('/')({
component: () => (
<section>
<h1>Welcome to the shop</h1>
<Link to="/products">See all products</Link>
</section>
),
})7. Starting the app
tsx
// src/router.tsx
import { createRouter } from '@tanstack/react-router'
import { QueryClient } from '@tanstack/react-query'
import { routeTree } from './routeTree.gen'
export const queryClient = new QueryClient()
export const router = createRouter({
routeTree,
context: { queryClient },
defaultPreload: 'intent',
})
declare module '@tanstack/react-router' {
interface Register {
router: typeof router
}
}tsx
// src/main.tsx
import { createRoot } from 'react-dom/client'
import { RouterProvider } from '@tanstack/react-router'
import { QueryClientProvider } from '@tanstack/react-query'
import { queryClient, router } from './router'
import { fakeFetch } from './api/fakeServer'
window.fetch = fakeFetch as typeof fetch // delete this line when you have a real server
createRoot(document.getElementById('root')!).render(
<QueryClientProvider client={queryClient}>
<RouterProvider router={router} />
</QueryClientProvider>,
)8. Follow one customer through the app
We ran this whole path in a test browser. Read it as a trace of which tool did what.
- The customer opens
/products?q=lamp. The router matches the products route.validateSearchacceptsq: 'lamp'.loaderDepssays the loader depends onq. The loader asks the Query cache. It is empty, so one request goes out:GET /api/products?q=lamp. The reply is checked byproductSchema. It goes into the cache under['products', 'list', { q: 'lamp' }]. The page draws "Desk lamp". - They click "Desk lamp". The router moves to
/products/p2. The loader fills['products', 'detail', 'p2']. The page draws the product with an "Add to cart" button. - They press "Add to cart".
addItemruns in the Zustand store. The header, which selects only the count, re-renders and showsCart (1). The product page does not re-render. The cart is written tolocalStorage. - They open
/cart, then/checkout. The cart page reads items from the store. The checkout page builds a form with React Hook Form. - They press "Place order" with the name empty.
handleSubmitrunscheckoutSchemathrough the resolver. Two messages appear. Nothing was sent to the server. - They fix the fields and submit again. The values are valid. The mutation runs
placeOrder, which combines the form values with the cart lines and posts them. The reply is checked byorderReceiptSchema. - On success, the cart is cleared and the router navigates to
/thanks/o-1001. The page shows the order number. The header saysCart (0).
Count the data stores involved: the URL held the search and the product id, Query held the server data, Zustand held the cart, React Hook Form held the form. Nothing was in two places at once.
9. Where to take it next
This shop is deliberately small. These are the natural next steps, and you now know the tool for each:
| You want | Use | Page |
|---|---|---|
| The heart icon that fills instantly | Optimistic update with onMutate | 6.4.11 |
| A server error such as "out of stock" shown beside a field | setError | 6.4.14 |
| A login and a protected "My orders" page | beforeLoad and a _auth folder | 6.4.12 |
| Several order lines edited at checkout | useFieldArray | 6.4.14 |
| Server rendering and a framework | Chapter 6.5 | |
| Styling | Chapter 6.2 | |
| Making it fast | Chapter 6.7 |
And if your team uses React Router instead of TanStack Router, the shop is built the same way: replace the route files with the route table from page 6.4.9, the loaders call queryClient.ensureQueryData the same way (page 6.4.11), and everything else is unchanged. That is the point of giving each tool one job.
What the interviewer will push on
"Walk me through the architecture of a React app you would build." Use this page as the answer. Name the kinds of state (server, URL, client, form, local) and their owners (Query, router, Zustand or Redux, React Hook Form, useState), and say what Zod does at the edges. The wrong answer is "I would put everything in Redux".
"How do you avoid duplicated state?" One owner per piece. Derive counts and totals with selectors. Never copy query data into useState. Put filters in the URL.
"Where do you validate?" At every boundary: the form (Zod resolver), the URL (validateSearch), the network reply (safeParse in the client). And again on the server, because the front end can be bypassed.
"How do the router and the query cache work together?" The loader calls ensureQueryData so the page has data on first draw. The component reads the same key with useSuspenseQuery so later changes (mutations, refetches) update the page.
"What would you change for a larger team or app?" Group by feature (features/cart, features/checkout), generate the API client and schemas from an API description, add error reporting, and consider server rendering. Show that you can scale the structure rather than only make it work.
One thing to volunteer: point out that a single Zod schema is imported by the form, the API client and the route, so a rule is written once and enforced everywhere.
Self-test: For each of these, name the owner and the page that taught it: the product list · the search text · the cart · the checkout error messages · "is this reply shaped right?" · "is the menu open?"
Next: The React chapter is complete. Page 6.4.16 covers composition patterns, portals, Suspense and error boundaries, the parts of React that are conventions rather than mechanisms. After this chapter, Chapter 6.5 adds the server (Next.js and server rendering), Chapter 6.6 covers the build tools that turn your files into a website, and Chapter 6.7 goes deeper on performance.