{"id":"6b09417f5ce40d447918f2d5","slug":"react","title":"Nowoczesny React 19 w praktyce – hooki, TanStack Query, formularze i routing","summary":"Budujemy kompletną aplikację zamówień pierogarni w React 19 – komponenty, hooki (stan, efekty, memo, ref, kontekst), pobieranie danych z TanStack Query, formularz z react-hook-form i Zod, routing w React Router 8, struktura projektu i wydajność.","servedLang":"pl","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":24,"stats":{"views":2,"likes":0,"bookmarks":0,"comments":0},"publishedAt":"2026-11-27T08:38:23.306Z","updatedAt":"2026-11-27T10:04:15.826Z","requestedLang":"pl","theme":{"hero":"classic","heroMedia":null,"accent":"indigo","background":"dots","weaveResources":true,"toc":"right"},"seoDescription":"React 19 krok po kroku – useState, useReducer, useEffect, useMemo, useRef, use(), TanStack Query (queryOptions, useSuspenseQuery, useMutation), react-hook-form + Zod, React Router 8 (loadery, lazy), struktura folderów, React Compiler i typowe błędy.","wordCount":4615,"doc":{"type":"doc","content":[{"type":"paragraph","content":[{"type":"text","text":"React 19 to już nie tylko "},{"type":"text","text":"useState","marks":[{"type":"code"}]},{"type":"text","text":" i "},{"type":"text","text":"useEffect","marks":[{"type":"code"}]},{"type":"text","text":". Dane z serwera obsługuje dziś osobna warstwa (TanStack Query), formularze – biblioteka, która nie renderuje komponentu przy każdym naciśnięciu klawisza, a routing potrafi pobrać dane, zanim strona się pokaże. W tym poradniku zbudujesz od zera aplikację zamówień pierogarni i zobaczysz, które narzędzie do czego służy i gdzie najczęściej popełnia się błędy."}]},{"type":"callout","attrs":{"variant":"info","title":"W skrócie"},"content":[{"type":"bulletList","content":[{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"Stan serwera to nie stan UI.","marks":[{"type":"bold"}]},{"type":"text","text":" Menu i zamówienia pobiera, cache'uje i odświeża TanStack Query. W "},{"type":"text","text":"useState","marks":[{"type":"code"}]},{"type":"text","text":"/kontekście zostaje tylko to, co naprawdę należy do przeglądarki: koszyk, filtr, otwarty panel."}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"useEffect","marks":[{"type":"code"}]},{"type":"text","text":" służy do synchronizacji z systemami zewnętrznymi","marks":[{"type":"bold"}]},{"type":"text","text":" (localStorage, zdarzenia przeglądarki, WebSocket). Danych pochodnych nie trzymasz w stanie – liczysz je w trakcie renderowania."}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"Formularz = schemat Zod + react-hook-form","marks":[{"type":"bold"}]},{"type":"text","text":": jedno źródło reguł walidacji i typów, mało renderowań, czytelne błędy. Wysyłka idzie przez "},{"type":"text","text":"useMutation","marks":[{"type":"code"}]},{"type":"text","text":"."}]}]}]}]},{"type":"callout","attrs":{"variant":"tip","title":"Co zbudujesz"},"content":[{"type":"paragraph","content":[{"type":"text","text":"Aplikację „Pierogarnia” w Vite + React 19 + TypeScript: menu z wyszukiwarką (skrót klawiszowy "},{"type":"text","text":"/","marks":[{"type":"code"}]},{"type":"text","text":"), koszyk zapisywany w "},{"type":"text","text":"localStorage","marks":[{"type":"code"}]},{"type":"text","text":", formularz zamówienia z walidacją i warunkowym polem godziny dostawy oraz stronę zamówienia, która co 3 sekundy odpytuje serwer o status. Backend to mała atrapa API (mock) uruchamiana przez serwer deweloperski Vite – po "},{"type":"text","text":"npm install && npm run dev","marks":[{"type":"code"}]},{"type":"text","text":" wszystko działa bez dodatkowych usług. Kod (23 pliki) pobierzesz jako ZIP ikoną pobierania przy artykule."}]}]},{"type":"paragraph","content":[{"type":"text","text":"Wymagania wstępne:","marks":[{"type":"bold"}]},{"type":"text","text":" Node.js 22.22+ (zalecany 24), podstawy JavaScriptu i TypeScriptu (typy, unie, generyki – patrz "},{"type":"text","text":"poradnik TypeScript","marks":[{"type":"link","attrs":{"href":"/pl/articles/typescript"}}]},{"type":"text","text":"), znajomość HTML/CSS. React na poziomie „wiem, co to komponent i props” wystarczy."}]},{"type":"stats","attrs":{"items":[{"value":"19","label":"wersja React","hint":"`use()`, `<title>` w komponencie, `ref` jako prop"},{"value":"5","label":"bibliotek","hint":"TanStack Query, react-hook-form, Zod, React Router, Vite"},{"value":"4","label":"trasy","hint":"menu, koszyk, checkout (lazy), zamówienie"},{"value":"0","label":"`useEffect` do pobierania danych","hint":"robi to TanStack Query"}]}},{"type":"diagram","attrs":{"kind":"mermaid","code":"flowchart TB\n  subgraph Providers[\"main.tsx\"]\n    QC[\"QueryClientProvider<br/>(cache stanu serwera)\"] --> CP[\"CartProvider<br/>(useReducer + localStorage)\"] --> RP[\"RouterProvider\"]\n  end\n  RP --> L[\"RootLayout<br/>nawigacja + 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/>w serwerze Vite\")]\n  O -->|\"GET /api/orders/:id co 3 s\"| API\n  M -->|\"GET /api/menu\"| API","caption":"Architektura aplikacji: gdzie żyje który stan"}},{"type":"heading","attrs":{"level":2,"id":"krok-1-projekt-i-struktura-katalogow"},"content":[{"type":"text","text":"Krok 1. Projekt i struktura katalogów"}]},{"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":"Zamiast dzielić kod według typu pliku ("},{"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":"), grupuj go według "},{"type":"text","text":"funkcji (feature)","marks":[{"type":"bold"}]},{"type":"text","text":". Wszystko, co dotyczy koszyka, leży obok siebie, a usunięcie funkcji to usunięcie jednego folderu."}]},{"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":"Co zawiera"}]}]}]},{"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":"start aplikacji: router, klient zapytań, layout, strona błędu"}]}]}]},{"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":"komponenty, hooki, schematy i zapytania jednej funkcji"}]}]}]},{"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":"kod bez wiedzy o domenie: klient HTTP, formatowanie, przyciski"}]}]}]},{"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":"atrapa API dla serwera deweloperskiego"}]}]}]}]},{"type":"paragraph","content":[{"type":"text","text":"Zasada importów: "},{"type":"text","text":"features/*","marks":[{"type":"code"}]},{"type":"text","text":" mogą korzystać z "},{"type":"text","text":"shared/","marks":[{"type":"code"}]},{"type":"text","text":", ale "},{"type":"text","text":"shared/","marks":[{"type":"code"}]},{"type":"text","text":" nie importuje niczego z "},{"type":"text","text":"features/","marks":[{"type":"code"}]},{"type":"text","text":". Plik konfiguracyjny, atrapa API i style:"}]},{"type":"codeGroup","attrs":{"title":"Konfiguracja, mock API i style"},"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":"Atrapa API to wtyczka Vite ("},{"type":"text","text":"configureServer","marks":[{"type":"code"}]},{"type":"text","text":"), która obsługuje "},{"type":"text","text":"/api/menu","marks":[{"type":"code"}]},{"type":"text","text":" i "},{"type":"text","text":"/api/orders","marks":[{"type":"code"}]},{"type":"text","text":" w pamięci, z losowym opóźnieniem 300–700 ms – dzięki temu zobaczysz prawdziwe stany ładowania. W produkcji ten sam kod frontendu rozmawia z prawdziwym backendem, bo adresy ("},{"type":"text","text":"/api/...","marks":[{"type":"code"}]},{"type":"text","text":") się nie zmieniają."}]},{"type":"heading","attrs":{"level":2,"id":"krok-2-komponenty-i-props"},"content":[{"type":"text","text":"Krok 2. Komponenty i props"}]},{"type":"paragraph","content":[{"type":"text","text":"Komponent to funkcja, która z propsów i stanu zwraca opis interfejsu. Trzy zasady, które oszczędzą Ci większości problemów:"}]},{"type":"orderedList","attrs":{"start":1},"content":[{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"Czystość","marks":[{"type":"bold"}]},{"type":"text","text":" – ten sam input daje ten sam JSX. Żadnych zapytań HTTP ani zapisu do "},{"type":"text","text":"localStorage","marks":[{"type":"code"}]},{"type":"text","text":" w ciele komponentu."}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"Dane w dół, zdarzenia w górę","marks":[{"type":"bold"}]},{"type":"text","text":" – "},{"type":"text","text":"MenuItemCard","marks":[{"type":"code"}]},{"type":"text","text":" dostaje "},{"type":"text","text":"item","marks":[{"type":"code"}]},{"type":"text","text":" i "},{"type":"text","text":"quantity","marks":[{"type":"code"}]},{"type":"text","text":", a o kliknięciu informuje przez "},{"type":"text","text":"onAdd","marks":[{"type":"code"}]},{"type":"text","text":". Nie wie, gdzie jest koszyk."}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"Kompozycja przez ","marks":[{"type":"bold"}]},{"type":"text","text":"children","marks":[{"type":"code"}]},{"type":"text","text":" – rodzic wstawia do karty dodatkową treść (np. etykietę „Vegetarian”), zamiast dokładać kolejne propsy typu "},{"type":"text","text":"showBadge","marks":[{"type":"code"}]},{"type":"text","text":"."}]}]}]},{"type":"codeGroup","attrs":{"title":"Komponent prezentacyjny"},"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":"krok-3-stan-i-hooki-usestate-usereducer-useeffect-usememo-useref"},"content":[{"type":"text","text":"Krok 3. Stan i hooki: useState, useReducer, useEffect, useMemo, useRef"}]},{"type":"paragraph","content":[{"type":"text","text":"Koszyk jest dobrym przykładem stanu UI: należy do przeglądarki, przeżywa odświeżenie strony i potrzebuje go kilka ekranów. Dlatego trzymasz go w "},{"type":"text","text":"useReducer","marks":[{"type":"code"}]},{"type":"text","text":" + kontekst","marks":[{"type":"bold"}]},{"type":"text","text":", a nie w 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":"Do czego"}]}]},{"type":"tableHeader","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Czego nim nie rób"}]}]}]},{"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":"prosta wartość lokalna: pole wyszukiwania, przełącznik"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"nie kopiuj do stanu propsów ani danych pochodnych"}]}]}]},{"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":"stan z kilkoma operacjami (dodaj, zmień ilość, wyczyść)"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"nie mieszaj w reducerze efektów ubocznych"}]}]}]},{"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":"dostęp do wspólnego stanu bez przekazywania propsów"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"nie wrzucaj tam wszystkiego – każda zmiana renderuje konsumentów"}]}]}]},{"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":"synchronizacja z systemem zewnętrznym + sprzątanie"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"nie licz w nim danych pochodnych i nie pobieraj danych ręcznie"}]}]}]},{"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":"stabilna referencja lub kosztowne obliczenie"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"nie owijaj każdej linijki – mierz, zanim zoptymalizujesz"}]}]}]},{"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":"uchwyt do elementu DOM, wartość bez renderowania (ID timera)"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"nie czytaj "},{"type":"text","text":"ref.current","marks":[{"type":"code"}]},{"type":"text","text":" w trakcie renderowania"}]}]}]}]},{"type":"codeGroup","attrs":{"title":"Koszyk: reducer, kontekst i strona"},"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":"krok-1-projekt-i-struktura-katalogow","text":"Krok 1. Projekt i struktura katalogów","level":2,"locked":false},{"id":"krok-2-komponenty-i-props","text":"Krok 2. Komponenty i props","level":2,"locked":false},{"id":"krok-3-stan-i-hooki-usestate-usereducer-useeffect-usememo-useref","text":"Krok 3. Stan i hooki: useState, useReducer, useEffect, useMemo, useRef","level":2,"locked":false},{"id":"krok-4-pobieranie-danych-z-tanstack-query","text":"Krok 4. Pobieranie danych z TanStack Query","level":2,"locked":true},{"id":"krok-5-formularz-react-hook-form-zod","text":"Krok 5. Formularz: react-hook-form + Zod","level":2,"locked":true},{"id":"krok-6-routing-w-react-router-8","text":"Krok 6. Routing w React Router 8","level":2,"locked":true},{"id":"krok-7-wydajnosc","text":"Krok 7. Wydajność","level":2,"locked":true},{"id":"typowe-bledy","text":"Typowe błędy","level":2,"locked":true},{"id":"sprawdz-sie","text":"Sprawdź się","level":2,"locked":true},{"id":"co-dalej","text":"Co dalej","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":"Autorytet","articles":63},{"key":"dotnet","title":".NET","level":5,"levelLabel":"Autorytet","articles":53},{"key":"python","title":"Python","level":5,"levelLabel":"Autorytet","articles":52},{"key":"java","title":"Java","level":5,"levelLabel":"Autorytet","articles":38}]}}