{"id":"6b09417f5ce40d447918f2d5","slug":"react","title":"Modern React 19 in practice – hooks, TanStack Query, forms and routing","summary":"We build a complete ordering app for a dumpling shop in React 19 – components, hooks (state, effects, memo, ref, context), data fetching with TanStack Query, a form with react-hook-form and Zod, routing with React Router 8, project structure and performance.","servedLang":"en","availableLangs":["pl","en"],"topics":["react","typescript"],"techs":["typescript","javascript"],"tags":["react-19","tanstack-query","react-hook-form","zod","react-router","vite","hooks","react-compiler"],"level":"intermediate","kind":"tutorial","access":"members","status":"published","cover":null,"author":{"id":"6b08bd2e80884893657cc8cf","name":"Redakcja Art of Devs","avatar":null,"handle":"redakcja","community":false},"readingMinutes":25,"stats":{"views":3,"likes":0,"bookmarks":0,"comments":0},"publishedAt":"2026-11-27T08:38:23.306Z","updatedAt":"2026-11-27T12:57:51.894Z","requestedLang":"en","theme":{"hero":"classic","heroMedia":null,"accent":"indigo","background":"dots","weaveResources":true,"toc":"right"},"seoDescription":"React 19 step by step – useState, useReducer, useEffect, useMemo, useRef, use(), TanStack Query (queryOptions, useSuspenseQuery, useMutation), react-hook-form + Zod, React Router 8 (loaders, lazy), folder structure, React Compiler and common mistakes.","wordCount":4817,"doc":{"type":"doc","content":[{"type":"paragraph","content":[{"type":"text","text":"React 19 is more than "},{"type":"text","text":"useState","marks":[{"type":"code"}]},{"type":"text","text":" and "},{"type":"text","text":"useEffect","marks":[{"type":"code"}]},{"type":"text","text":". Server data is now handled by a dedicated layer (TanStack Query), forms by a library that doesn't re-render the component on every keystroke, and the router can fetch data before a page even shows up. In this guide you'll build a dumpling shop ordering app from scratch and see which tool does what – and where people most often go wrong."}]},{"type":"callout","attrs":{"variant":"info","title":"In short"},"content":[{"type":"bulletList","content":[{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"Server state isn't UI state.","marks":[{"type":"bold"}]},{"type":"text","text":" TanStack Query fetches, caches and refreshes the menu and orders. "},{"type":"text","text":"useState","marks":[{"type":"code"}]},{"type":"text","text":"/context only keep what truly belongs to the browser: the cart, a filter, an open panel."}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"useEffect","marks":[{"type":"code"}]},{"type":"text","text":" is for synchronising with external systems","marks":[{"type":"bold"}]},{"type":"text","text":" (localStorage, browser events, WebSockets). Derived data doesn't live in state – you compute it during render."}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"A form = a Zod schema + react-hook-form","marks":[{"type":"bold"}]},{"type":"text","text":": one source of validation rules and types, few re-renders, clear errors. Submission goes through "},{"type":"text","text":"useMutation","marks":[{"type":"code"}]},{"type":"text","text":"."}]}]}]}]},{"type":"callout","attrs":{"variant":"tip","title":"What you'll build"},"content":[{"type":"paragraph","content":[{"type":"text","text":"A \"Pierogarnia\" app in Vite + React 19 + TypeScript: a menu with search (keyboard shortcut "},{"type":"text","text":"/","marks":[{"type":"code"}]},{"type":"text","text":"), a cart persisted in "},{"type":"text","text":"localStorage","marks":[{"type":"code"}]},{"type":"text","text":", an order form with validation and a conditional delivery-time field, and an order page that polls the server for status every 3 seconds. The backend is a small mock API served by the Vite dev server – after "},{"type":"text","text":"npm install && npm run dev","marks":[{"type":"code"}]},{"type":"text","text":" everything works with no extra services. The code (23 files) downloads as a ZIP from the download icon next to the article."}]}]},{"type":"paragraph","content":[{"type":"text","text":"Prerequisites:","marks":[{"type":"bold"}]},{"type":"text","text":" Node.js 22.22+ (24 recommended), JavaScript and TypeScript basics (types, unions, generics – see the "},{"type":"text","text":"TypeScript guide","marks":[{"type":"link","attrs":{"href":"/en/articles/typescript"}}]},{"type":"text","text":"), HTML/CSS. React at the \"I know what a component and props are\" level is enough."}]},{"type":"stats","attrs":{"items":[{"value":"19","label":"React version","hint":"`use()`, `<title>` in components, `ref` as a prop"},{"value":"5","label":"libraries","hint":"TanStack Query, react-hook-form, Zod, React Router, Vite"},{"value":"4","label":"routes","hint":"menu, cart, checkout (lazy), order"},{"value":"0","label":"`useEffect`s for fetching","hint":"TanStack Query does it"}]}},{"type":"diagram","attrs":{"kind":"mermaid","code":"flowchart TB\n  subgraph Providers[\"main.tsx\"]\n    QC[\"QueryClientProvider<br/>(server state cache)\"] --> CP[\"CartProvider<br/>(useReducer + localStorage)\"] --> RP[\"RouterProvider\"]\n  end\n  RP --> L[\"RootLayout<br/>navigation + Outlet\"]\n  L --> M[\"MenuPage<br/>useSuspenseQuery(menu)\"]\n  L --> C[\"CartPage<br/>useCart()\"]\n  L --> K[\"CheckoutPage (lazy)<br/>useForm + useMutation\"]\n  L --> O[\"OrderPage<br/>useQuery(order, polling)\"]\n  M -. \"loader: ensureQueryData\" .-> QC\n  K -->|\"POST /api/orders\"| API[(\"Mock API<br/>in the Vite server\")]\n  O -->|\"GET /api/orders/:id every 3 s\"| API\n  M -->|\"GET /api/menu\"| API","caption":"App architecture: where each kind of state lives"}},{"type":"heading","attrs":{"level":2,"id":"step-1-project-and-folder-structure"},"content":[{"type":"text","text":"Step 1. Project and folder structure"}]},{"type":"codeBlock","attrs":{"language":"bash"},"content":[{"type":"text","text":"npm create vite@latest pierogi-react -- --template react-ts\ncd pierogi-react\nnpm install @tanstack/react-query react-router react-hook-form @hookform/resolvers zod\nnpm run dev"}]},{"type":"paragraph","content":[{"type":"text","text":"Instead of splitting code by file type ("},{"type":"text","text":"components/","marks":[{"type":"code"}]},{"type":"text","text":", "},{"type":"text","text":"hooks/","marks":[{"type":"code"}]},{"type":"text","text":", "},{"type":"text","text":"services/","marks":[{"type":"code"}]},{"type":"text","text":"), group it by "},{"type":"text","text":"feature","marks":[{"type":"bold"}]},{"type":"text","text":". Everything about the cart sits together, and removing a feature means deleting one folder."}]},{"type":"table","content":[{"type":"tableRow","content":[{"type":"tableHeader","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Folder"}]}]},{"type":"tableHeader","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"What it holds"}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"src/app/","marks":[{"type":"code"}]}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"app bootstrap: router, query client, layout, error page"}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"src/features/menu/","marks":[{"type":"code"}]},{"type":"text","text":", "},{"type":"text","text":"cart/","marks":[{"type":"code"}]},{"type":"text","text":", "},{"type":"text","text":"checkout/","marks":[{"type":"code"}]},{"type":"text","text":", "},{"type":"text","text":"orders/","marks":[{"type":"code"}]}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"components, hooks, schemas and queries of one feature"}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"src/shared/","marks":[{"type":"code"}]}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"domain-agnostic code: HTTP client, formatting, buttons"}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"mock/","marks":[{"type":"code"}]}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"the mock API for the dev server"}]}]}]}]},{"type":"paragraph","content":[{"type":"text","text":"Import rule: "},{"type":"text","text":"features/*","marks":[{"type":"code"}]},{"type":"text","text":" may use "},{"type":"text","text":"shared/","marks":[{"type":"code"}]},{"type":"text","text":", but "},{"type":"text","text":"shared/","marks":[{"type":"code"}]},{"type":"text","text":" imports nothing from "},{"type":"text","text":"features/","marks":[{"type":"code"}]},{"type":"text","text":". The config files, mock API and styles:"}]},{"type":"codeGroup","attrs":{"title":"Configuration, mock API and styles"},"content":[{"type":"codeBlock","attrs":{"language":"json","filename":"package.json"},"content":[{"type":"text","text":"{\n  \"name\": \"pierogi-react\",\n  \"private\": true,\n  \"version\": \"0.1.0\",\n  \"type\": \"module\",\n  \"scripts\": {\n    \"dev\": \"vite\",\n    \"build\": \"tsc --noEmit && vite build\",\n    \"preview\": \"vite preview\"\n  },\n  \"dependencies\": {\n    \"@hookform/resolvers\": \"^7.0.9\",\n    \"@tanstack/react-query\": \"^5.108.4\",\n    \"react\": \"^19.3.1\",\n    \"react-dom\": \"^19.3.1\",\n    \"react-hook-form\": \"^7.92.0\",\n    \"react-router\": \"^8.5.3\",\n    \"zod\": \"^4.6.7\"\n  },\n  \"devDependencies\": {\n    \"@types/node\": \"^24.0.0\",\n    \"@types/react\": \"^19.3.0\",\n    \"@types/react-dom\": \"^19.3.0\",\n    \"@vitejs/plugin-react\": \"^6.3.0\",\n    \"typescript\": \"~7.0.2\",\n    \"vite\": \"^8.4.0\"\n  }\n}"}]},{"type":"codeBlock","attrs":{"language":"json","filename":"tsconfig.json"},"content":[{"type":"text","text":"{\n  \"compilerOptions\": {\n    \"target\": \"es2023\",\n    \"lib\": [\"ES2023\", \"DOM\", \"DOM.Iterable\"],\n    \"module\": \"esnext\",\n    \"moduleResolution\": \"bundler\",\n    \"types\": [\"vite/client\", \"node\"],\n    \"jsx\": \"react-jsx\",\n    \"noEmit\": true,\n    \"allowImportingTsExtensions\": true,\n    \"verbatimModuleSyntax\": true,\n    \"erasableSyntaxOnly\": true,\n    \"skipLibCheck\": true,\n    \"noUncheckedIndexedAccess\": true,\n    \"noUnusedLocals\": true\n  },\n  \"include\": [\"src\", \"mock\", \"vite.config.ts\"]\n}"}]},{"type":"codeBlock","attrs":{"language":"typescript","filename":"vite.config.ts"},"content":[{"type":"text","text":"import react from \"@vitejs/plugin-react\";\nimport { defineConfig } from \"vite\";\nimport { mockApi } from \"./mock/api.ts\";\n\nexport default defineConfig({\n  plugins: [react(), mockApi()],\n});"}]},{"type":"codeBlock","attrs":{"language":"typescript","filename":"mock/api.ts"},"content":[{"type":"text","text":"import type { IncomingMessage, ServerResponse } from \"node:http\";\nimport type { Plugin } from \"vite\";\n\n// A tiny in-memory API served by the Vite dev server – just enough to make the app real.\nconst menu = [\n  { id: \"ruskie\", name: \"Ruskie\", description: \"Potato, twaróg, fried onion\", priceCents: 3200, vegetarian: true },\n  { id: \"meat\", name: \"Z mięsem\", description: \"Slow-cooked pork and beef\", priceCents: 3600, vegetarian: false },\n  { id: \"cabbage\", name: \"Kapusta i grzyby\", description: \"Sauerkraut and forest mushrooms\", priceCents: 3400, vegetarian: true },\n  { id: \"spinach\", name: \"Szpinak i feta\", description: \"Spinach, feta, garlic\", priceCents: 3500, vegetarian: true },\n  { id: \"duck\", name: \"Z kaczką\", description: \"Duck with apple, cranberry sauce\", priceCents: 4400, vegetarian: false },\n];\n\ntype StoredOrder = { id: string; createdAt: number; customer: { name: string; address: string }; lines: unknown[] };\nconst orders = new Map<string, StoredOrder>();\n\n// The status moves forward with time, so polling in the UI has something to show.\nfunction statusOf(order: StoredOrder) {\n  const seconds = (Date.now() - order.createdAt) / 1000;\n  if (seconds < 10) return \"placed\";\n  if (seconds < 25) return \"cooking\";\n  if (seconds < 45) return \"delivering\";\n  return \"delivered\";\n}\n\nconst send = (res: ServerResponse, status: number, body: unknown) => {\n  res.statusCode = status;\n  res.setHeader(\"Content-Type\", \"application/json\");\n  setTimeout(() => res.end(JSON.stringify(body)), 300 + Math.random() * 400); // fake latency\n};\n\nasync function readJson(req: IncomingMessage): Promise<unknown> {\n  let raw = \"\";\n  for await (const chunk of req) raw += chunk;\n  return JSON.parse(raw || \"{}\");\n}\n\nexport function mockApi(): Plugin {\n  return {\n    name: \"mock-api\",\n    configureServer(server) {\n      server.middlewares.use(\"/api\", async (req, res) => {\n        const url = req.url ?? \"/\";\n        if (req.method === \"GET\" && url === \"/menu\") return send(res, 200, menu);\n        if (req.method === \"POST\" && url === \"/orders\") {\n          const body = (await readJson(req)) as Omit<StoredOrder, \"id\" | \"createdAt\">;\n          const order = { ...body, id: String(1000 + orders.size + 1), createdAt: Date.now() };\n          orders.set(order.id, order);\n          return send(res, 201, { ...order, status: statusOf(order) });\n        }\n        const match = /^\\/orders\\/(\\w+)$/.exec(url);\n        const order = match?.[1] ? orders.get(match[1]) : undefined;\n        if (req.method === \"GET\" && order) return send(res, 200, { ...order, status: statusOf(order) });\n        send(res, 404, { message: \"Not found\" });\n      });\n    },\n  };\n}"}]},{"type":"codeBlock","attrs":{"language":"html","filename":"index.html"},"content":[{"type":"text","text":"<!doctype html>\n<html lang=\"en\">\n  <head>\n    <meta charset=\"UTF-8\" />\n    <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\" />\n    <title>Pierogarnia</title>\n  </head>\n  <body>\n    <div id=\"root\"></div>\n    <script type=\"module\" src=\"/src/main.tsx\"></script>\n  </body>\n</html>"}]},{"type":"codeBlock","attrs":{"language":"css","filename":"src/index.css"},"content":[{"type":"text","text":":root { font-family: system-ui, sans-serif; color: #1f2328; background: #f6f7f9; }\nbody { margin: 0; }\na { color: #4263eb; }\n.layout { max-width: 880px; margin: 0 auto; padding: 16px; }\n.topbar { display: flex; gap: 16px; align-items: center; padding: 12px 0; border-bottom: 1px solid #dee2e6; }\n.topbar .active { font-weight: 700; text-decoration: none; }\n.progress { height: 3px; background: #4263eb; animation: grow 1s ease-out infinite; }\n@keyframes grow { from { width: 0; } to { width: 100%; } }\n.grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(240px, 1fr)); gap: 12px; }\n.card { background: #fff; border: 1px solid #dee2e6; border-radius: 8px; padding: 12px; display: grid; gap: 8px; }\n.field { display: grid; gap: 4px; margin-bottom: 12px; }\n.field input, .field select, .field textarea { padding: 8px; border: 1px solid #ced4da; border-radius: 6px; font: inherit; }\n.error { color: #c92a2a; font-size: 0.875rem; }\nbutton { padding: 8px 12px; border-radius: 6px; border: 1px solid #4263eb; background: #4263eb; color: #fff; cursor: pointer; }\nbutton:disabled { opacity: 0.6; cursor: wait; }"}]}]},{"type":"paragraph","content":[{"type":"text","text":"The mock API is a Vite plugin ("},{"type":"text","text":"configureServer","marks":[{"type":"code"}]},{"type":"text","text":") that serves "},{"type":"text","text":"/api/menu","marks":[{"type":"code"}]},{"type":"text","text":" and "},{"type":"text","text":"/api/orders","marks":[{"type":"code"}]},{"type":"text","text":" from memory with a random 300–700 ms delay, so you'll see real loading states. In production the same frontend talks to a real backend, because the URLs ("},{"type":"text","text":"/api/...","marks":[{"type":"code"}]},{"type":"text","text":") stay the same."}]},{"type":"heading","attrs":{"level":2,"id":"step-2-components-and-props"},"content":[{"type":"text","text":"Step 2. Components and props"}]},{"type":"paragraph","content":[{"type":"text","text":"A component is a function that turns props and state into a description of the UI. Three rules that will spare you most problems:"}]},{"type":"orderedList","attrs":{"start":1},"content":[{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"Purity","marks":[{"type":"bold"}]},{"type":"text","text":" – the same input gives the same JSX. No HTTP calls or "},{"type":"text","text":"localStorage","marks":[{"type":"code"}]},{"type":"text","text":" writes in the component body."}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"Data down, events up","marks":[{"type":"bold"}]},{"type":"text","text":" – "},{"type":"text","text":"MenuItemCard","marks":[{"type":"code"}]},{"type":"text","text":" receives "},{"type":"text","text":"item","marks":[{"type":"code"}]},{"type":"text","text":" and "},{"type":"text","text":"quantity","marks":[{"type":"code"}]},{"type":"text","text":" and reports clicks via "},{"type":"text","text":"onAdd","marks":[{"type":"code"}]},{"type":"text","text":". It has no idea where the cart lives."}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"Composition via ","marks":[{"type":"bold"}]},{"type":"text","text":"children","marks":[{"type":"code"}]},{"type":"text","text":" – the parent puts extra content into the card (e.g. a \"Vegetarian\" label) instead of adding more props like "},{"type":"text","text":"showBadge","marks":[{"type":"code"}]},{"type":"text","text":"."}]}]}]},{"type":"codeGroup","attrs":{"title":"A presentational component"},"content":[{"type":"codeBlock","attrs":{"language":"typescript","filename":"src/shared/format.ts"},"content":[{"type":"text","text":"const pln = new Intl.NumberFormat(\"pl-PL\", { style: \"currency\", currency: \"PLN\" });\n\nexport const formatPrice = (cents: number) => pln.format(cents / 100);"}]},{"type":"codeBlock","attrs":{"language":"typescript","filename":"src/features/menu/MenuItemCard.tsx"},"content":[{"type":"text","text":"import type { ReactNode } from \"react\";\nimport { formatPrice } from \"../../shared/format.ts\";\nimport type { MenuItem } from \"./api.ts\";\n\ninterface MenuItemCardProps {\n  item: MenuItem;\n  quantity: number;\n  onAdd: (item: MenuItem) => void;\n  children?: ReactNode; // composition: the parent decides what extra content goes inside\n}\n\n// A presentational component: data in through props, events out through callbacks.\nexport function MenuItemCard({ item, quantity, onAdd, children }: MenuItemCardProps) {\n  return (\n    <article className=\"card\">\n      <header style={{ display: \"flex\", justifyContent: \"space-between\", gap: 8 }}>\n        <strong>{item.name}</strong>\n        <span>{formatPrice(item.priceCents)}</span>\n      </header>\n      <p style={{ margin: 0, color: \"#495057\" }}>{item.description}</p>\n      {children}\n      <button type=\"button\" onClick={() => onAdd(item)}>\n        {quantity > 0 ? `Add another (${quantity} in cart)` : \"Add to cart\"}\n      </button>\n    </article>\n  );\n}"}]}]},{"type":"heading","attrs":{"level":2,"id":"step-3-state-and-hooks-usestate-usereducer-useeffect-usememo-useref"},"content":[{"type":"text","text":"Step 3. State and hooks: useState, useReducer, useEffect, useMemo, useRef"}]},{"type":"paragraph","content":[{"type":"text","text":"The cart is a good example of UI state: it belongs to the browser, survives a page refresh and is needed by several screens. So it lives in "},{"type":"text","text":"useReducer","marks":[{"type":"code"}]},{"type":"text","text":" + context","marks":[{"type":"bold"}]},{"type":"text","text":", not in TanStack Query."}]},{"type":"table","content":[{"type":"tableRow","content":[{"type":"tableHeader","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Hook"}]}]},{"type":"tableHeader","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"What for"}]}]},{"type":"tableHeader","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Don't use it to"}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"useState","marks":[{"type":"code"}]}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"a simple local value: search text, a toggle"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"copy props or derived data into state"}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"useReducer","marks":[{"type":"code"}]}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"state with several operations (add, change quantity, clear)"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"run side effects inside the reducer"}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"use(Context)","marks":[{"type":"code"}]}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"share state without prop drilling"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"hold everything – every change re-renders all consumers"}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"useEffect","marks":[{"type":"code"}]}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"synchronise with an external system + clean up"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"compute derived data or fetch data by hand"}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"useMemo","marks":[{"type":"code"}]}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"a stable reference or an expensive calculation"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"wrap every line – measure before you optimise"}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"useRef","marks":[{"type":"code"}]}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"a handle to a DOM node, a value that doesn't trigger renders (timer id)"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"read "},{"type":"text","text":"ref.current","marks":[{"type":"code"}]},{"type":"text","text":" during render"}]}]}]}]},{"type":"codeGroup","attrs":{"title":"Cart: reducer, context and page"},"content":[{"type":"codeBlock","attrs":{"language":"typescript","filename":"src/features/cart/cart-context.tsx"},"content":[{"type":"text","text":"import { createContext, use, useEffect, useMemo, useReducer, type ReactNode } from \"react\";\nimport { z } from \"zod\";\nimport type { MenuItem } from \"../menu/api.ts\";\n\nconst CartLineSchema = z.object({ id: z.string(), name: z.string(), priceCents: z.int(), quantity: z.int().positive() });\nexport type CartLine = z.infer<typeof CartLineSchema>;\n\ntype CartAction =\n  | { type: \"add\"; item: Pick<MenuItem, \"id\" | \"name\" | \"priceCents\"> }\n  | { type: \"setQuantity\"; id: string; quantity: number }\n  | { type: \"clear\" };\n\n// A reducer is a pure function: (state, action) => new state. Easy to test, no React needed.\nfunction cartReducer(lines: CartLine[], action: CartAction): CartLine[] {\n  switch (action.type) {\n    case \"add\": {\n      const existing = lines.find((l) => l.id === action.item.id);\n      return existing\n        ? lines.map((l) => (l.id === action.item.id ? { ...l, quantity: l.quantity + 1 } : l))\n        : [...lines, { ...action.item, quantity: 1 }];\n    }\n    case \"setQuantity\":\n      return action.quantity <= 0\n        ? lines.filter((l) => l.id !== action.id)\n        : lines.map((l) => (l.id === action.id ? { ...l, quantity: action.quantity } : l));\n    case \"clear\":\n      return [];\n  }\n}\n\nconst STORAGE_KEY = \"pierogi-cart\";\n\n// localStorage is external, untrusted data – validate it like an API response.\nfunction loadCart(): CartLine[] {\n  try {\n    const parsed = z.array(CartLineSchema).safeParse(JSON.parse(localStorage.getItem(STORAGE_KEY) ?? \"[]\"));\n    return parsed.success ? parsed.data : [];\n  } catch {\n    return [];\n  }\n}\n\ntype CartContextValue = {\n  lines: CartLine[];\n  count: number;\n  totalCents: number;\n  dispatch: (action: CartAction) => void;\n};\n\nconst CartContext = createContext<CartContextValue | null>(null);\n\nexport function CartProvider({ children }: { children: ReactNode }) {\n  // Third argument = lazy initializer: localStorage is read once, not on every render.\n  const [lines, dispatch] = useReducer(cartReducer, [], loadCart);\n\n  // useEffect synchronises React state with an external system (here: localStorage).\n  useEffect(() => {\n    localStorage.setItem(STORAGE_KEY, JSON.stringify(lines));\n  }, [lines]);\n\n  // useMemo keeps the context value stable, so consumers re-render only when the cart changes.\n  const value = useMemo(\n    () => ({\n      lines,\n      dispatch,\n      count: lines.reduce((n, l) => n + l.quantity, 0),\n      totalCents: lines.reduce((sum, l) => sum + l.quantity * l.priceCents, 0),\n    }),\n    [lines],\n  );\n\n  // React 19: the context itself is the provider, and use() reads it.\n  return <CartContext value={value}>{children}</CartContext>;\n}\n\nexport function useCart() {\n  const ctx = use(CartContext);\n  if (!ctx) throw new Error(\"useCart() must be used inside <CartProvider>\");\n  return ctx;\n}"}]},{"type":"codeBlock","attrs":{"language":"typescript","filename":"src/features/cart/CartPage.tsx"},"content":[{"type":"text","text":"import { Link } from \"react-router\";\nimport { formatPrice } from \"../../shared/format.ts\";\nimport { useCart } from \"./cart-context.tsx\";\n\nexport function CartPage() {\n  const { lines, totalCents, dispatch } = useCart();\n\n  if (lines.length === 0) {\n    return (\n      <p>\n        <title>Cart · Pierogarnia</title>\n        Your cart is empty. <Link to=\"/\">Browse the menu</Link>\n      </p>\n    );\n  }\n\n  return (\n    <section>\n      {/* React 19 hoists <title> into <head> – no effect or helmet library needed */}\n      <title>{`Cart (${lines.length}) · Pierogarnia`}</title>\n      <h1>Cart</h1>\n      <ul style={{ listStyle: \"none\", padding: 0, display: \"grid\", gap: 8 }}>\n        {lines.map((line) => (\n          <li key={line.id} className=\"card\" style={{ gridTemplateColumns: \"1fr auto auto\", alignItems: \"center\" }}>\n            <span>{line.name}</span>\n            <input\n              type=\"number\"\n              min={0}\n              max={50}\n              value={line.quantity}\n              aria-label={`Quantity of ${line.name}`}\n              onChange={(e) => dispatch({ type: \"setQuantity\", id: line.id, quantity: e.target.valueAsNumber || 0 })}\n              style={{ width: 64 }}\n            />\n            <span>{formatPrice(line.priceCents * line.quantity)}</span>\n          </li>\n        ))}\n      </ul>\n      <p>\n        <strong>Total: {formatPrice(totalCents)}</strong>\n      </p>\n      <Link to=\"/checkout\">Go to checkout →</Link>\n    </section>\n  );\n}"}]}]}]},"toc":[{"id":"step-1-project-and-folder-structure","text":"Step 1. Project and folder structure","level":2,"locked":false},{"id":"step-2-components-and-props","text":"Step 2. Components and props","level":2,"locked":false},{"id":"step-3-state-and-hooks-usestate-usereducer-useeffect-usememo-useref","text":"Step 3. State and hooks: useState, useReducer, useEffect, useMemo, useRef","level":2,"locked":false},{"id":"step-4-data-fetching-with-tanstack-query","text":"Step 4. Data fetching with TanStack Query","level":2,"locked":true},{"id":"step-5-a-form-react-hook-form-zod","text":"Step 5. A form: react-hook-form + Zod","level":2,"locked":true},{"id":"step-6-routing-with-react-router-8","text":"Step 6. Routing with React Router 8","level":2,"locked":true},{"id":"step-7-performance","text":"Step 7. Performance","level":2,"locked":true},{"id":"common-mistakes","text":"Common mistakes","level":2,"locked":true},{"id":"check-yourself","text":"Check yourself","level":2,"locked":true},{"id":"what-next","text":"What next","level":2,"locked":true}],"locked":true,"paywall":null,"previewRatio":0.3,"totalBlocks":57,"visibleBlocks":21,"resources":[{"id":"6b0857b13c96f2d34d0b335a","type":"article","provider":"devto","url":"https://dev.to/perssondennis/21-fantastic-react-design-patterns-and-when-to-use-them-7bb","embedUrl":null,"title":"21 Fantastic React Design Patterns and When to Use Them","description":"Design patterns aren't just for backend developers who can't say a sentence without mentioning...","author":"Dennis Persson","thumbnailUrl":"https://media2.dev.to/dynamic/image/width=1000,height=420,fit=cover,gravity=auto,format=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F01vzftwtkzrfk3ip2am2.png","durationSec":null,"lang":"en","topics":[],"techs":["javascript"],"tags":["design-patterns","software-architecture","react","webdev","architecture","designpatterns"],"price":"free","featured":false,"featuredOrder":0,"packageName":null,"source":"devto","publishedAt":"2025-08-24T14:41:00.000Z","popularity":50,"verifiedAt":"2026-11-26T10:52:10.000Z","curated":false,"addedBy":"6b0857a15a2625e44ecaabe6","createdAt":"2026-11-26T16:00:49.541Z","updatedAt":"2026-11-26T16:00:49.541Z"},{"id":"6b0857c53c96f2d34d0b479b","type":"book","provider":"openlibrary","url":"https://openlibrary.org/works/OL24207531W","embedUrl":null,"title":"React Design Patterns and Best Practices","description":"","author":"Carlos Santana Roldan","thumbnailUrl":"https://covers.openlibrary.org/b/id/10653332-L.jpg","durationSec":null,"lang":"en","topics":[],"techs":["javascript"],"tags":["book","design-patterns"],"price":"paid","featured":false,"featuredOrder":0,"packageName":null,"source":"openlibrary","publishedAt":"2019-01-01T00:00:00.000Z","popularity":24,"verifiedAt":"2026-11-26T11:00:08.000Z","curated":false,"addedBy":"6b0857a15a2625e44ecaabe6","createdAt":"2026-11-26T16:01:07.480Z","updatedAt":"2026-11-26T16:01:07.480Z"},{"id":"6b0857b33c96f2d34d0b3789","type":"article","provider":"web","url":"https://overreacted.io/goodbye-clean-code","embedUrl":null,"title":"Goodbye, Clean Code","description":"Let clean code guide you. Then let it go.","author":"overreacted.io","thumbnailUrl":"https://overreacted.io/goodbye-clean-code/opengraph-image?5b0b970dfd19bb8c","durationSec":null,"lang":"en","topics":[],"techs":["general"],"tags":["clean-code","hacker-news"],"price":"free","featured":false,"featuredOrder":0,"packageName":null,"source":"hn","publishedAt":"2020-01-11T21:32:07.000Z","popularity":93,"verifiedAt":"2026-11-26T11:07:41.000Z","curated":false,"addedBy":"6b0857a15a2625e44ecaabe6","createdAt":"2026-11-26T16:00:51.221Z","updatedAt":"2026-11-26T16:00:51.221Z"},{"id":"6b0857b73c96f2d34d0b3c08","type":"podcast","provider":"apple-podcasts","url":"https://podcasts.apple.com/pl/podcast/stan-frontendu-i-ekosystemu-js-2026-z-tomkiem-ducinem/id1477067604?i=1000761945996","embedUrl":"https://embed.podcasts.apple.com/us/podcast/id1477067604?i=1000761945996","title":"Stan frontendu i ekosystemu JS 2026 z Tomkiem Ducinem","description":"“Jest niejako absurdalne, że do tego, żeby zrobić podstronkę z formularzem, musisz myśleć o memoizacji referencji na funkcję.” Tomasz Ducin - konsultant, architekt i człowiek, który dekadę spędził na frontendzie - nie owija w bawełnę. 95% projektów frontendowych to niemodularne monolity, a…","author":"Patoarchitekci","thumbnailUrl":"https://is1-ssl.mzstatic.com/image/thumb/Podcasts221/v4/bf/af/0f/bfaf0fdb-b9b4-8dfb-b1b1-c66067bed53f/mza_11797970467840187143.jpg/600x600bb.jpg","durationSec":3542,"lang":"pl","topics":["modular-monolith","hexagonal-architecture"],"techs":["javascript"],"tags":["podcast","llm","ai","software-architecture"],"price":"free","featured":false,"featuredOrder":0,"packageName":null,"source":"itunes","publishedAt":"2026-04-17T06:00:03.000Z","popularity":68,"verifiedAt":"2026-11-26T11:07:41.000Z","curated":false,"addedBy":"6b0857a15a2625e44ecaabe6","createdAt":"2026-11-26T16:00:53.924Z","updatedAt":"2026-11-26T16:00:53.924Z"},{"id":"6b0857b23c96f2d34d0b34b7","type":"repo","provider":"github","url":"https://github.com/greatfrontend/awesome-front-end-system-design","embedUrl":null,"title":"greatfrontend/awesome-front-end-system-design","description":"Curated front end system design resources for interviews and learning","author":"greatfrontend","thumbnailUrl":"https://opengraph.githubassets.com/1/greatfrontend/awesome-front-end-system-design","durationSec":null,"lang":"en","topics":[],"techs":["javascript"],"tags":["front-end","front-end-system-design","javascript","react","system-design","system-design-interview"],"price":"free","featured":false,"featuredOrder":0,"packageName":null,"source":"github","publishedAt":"2023-01-25T05:08:57.000Z","popularity":76,"verifiedAt":"2026-11-26T10:58:46.000Z","curated":false,"addedBy":"6b0857a15a2625e44ecaabe6","createdAt":"2026-11-26T16:00:50.215Z","updatedAt":"2026-11-26T16:00:50.215Z"}],"challenges":[],"attachments":[],"hasCode":true,"repoUrl":null,"series":[],"prev":null,"next":null,"featured":false,"authorCard":{"id":"6b08bd2e80884893657cc8cf","name":"Redakcja Art of Devs","avatar":null,"handle":"redakcja","headline":"Wzorce projektowe · Architektura · AI i LLM","community":false,"reputation":{"points":3900,"level":{"key":"mentor","label":"Mentor"}},"articles":68,"skills":[{"key":"typescript","title":"TypeScript","level":5,"levelLabel":"Authority","articles":63},{"key":"dotnet","title":".NET","level":5,"levelLabel":"Authority","articles":53},{"key":"python","title":"Python","level":5,"levelLabel":"Authority","articles":52},{"key":"java","title":"Java","level":5,"levelLabel":"Authority","articles":38}]}}