Poradnik · React · TypeScript
Nowoczesny React 19 w praktyce – hooki, TanStack Query, formularze i routing
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ść.
React 19 to już nie tylko useState i useEffect. 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.
Wymagania wstępne: Node.js 22.22+ (zalecany 24), podstawy JavaScriptu i TypeScriptu (typy, unie, generyki – patrz poradnik TypeScript), znajomość HTML/CSS. React na poziomie „wiem, co to komponent i props” wystarczy.
- 19
- wersja React – `use()`, `<title>` w komponencie, `ref` jako prop
- 5
- bibliotek – TanStack Query, react-hook-form, Zod, React Router, Vite
- 4
- trasy – menu, koszyk, checkout (lazy), zamówienie
- 0
- `useEffect` do pobierania danych – robi to TanStack Query
Krok 1. Projekt i struktura katalogów
npm create vite@latest pierogi-react -- --template react-ts
cd pierogi-react
npm install @tanstack/react-query react-router react-hook-form @hookform/resolvers zod
npm run dev
Zamiast dzielić kod według typu pliku (components/, hooks/, services/), grupuj go według funkcji (feature). Wszystko, co dotyczy koszyka, leży obok siebie, a usunięcie funkcji to usunięcie jednego folderu.
| Folder | Co zawiera |
|---|---|
src/app/ | start aplikacji: router, klient zapytań, layout, strona błędu |
src/features/menu/, cart/, checkout/, orders/ | komponenty, hooki, schematy i zapytania jednej funkcji |
src/shared/ | kod bez wiedzy o domenie: klient HTTP, formatowanie, przyciski |
mock/ | atrapa API dla serwera deweloperskiego |
Zasada importów: features/* mogą korzystać z shared/, ale shared/ nie importuje niczego z features/. Plik konfiguracyjny, atrapa API i style:
Konfiguracja, mock API i style
{
"name": "pierogi-react",
"private": true,
"version": "0.1.0",
"type": "module",
"scripts": {
"dev": "vite",
"build": "tsc --noEmit && vite build",
"preview": "vite preview"
},
"dependencies": {
"@hookform/resolvers": "^7.0.9",
"@tanstack/react-query": "^5.108.4",
"react": "^19.3.1",
"react-dom": "^19.3.1",
"react-hook-form": "^7.92.0",
"react-router": "^8.5.3",
"zod": "^4.6.7"
},
"devDependencies": {
"@types/node": "^24.0.0",
"@types/react": "^19.3.0",
"@types/react-dom": "^19.3.0",
"@vitejs/plugin-react": "^6.3.0",
"typescript": "~7.0.2",
"vite": "^8.4.0"
}
}{
"compilerOptions": {
"target": "es2023",
"lib": ["ES2023", "DOM", "DOM.Iterable"],
"module": "esnext",
"moduleResolution": "bundler",
"types": ["vite/client", "node"],
"jsx": "react-jsx",
"noEmit": true,
"allowImportingTsExtensions": true,
"verbatimModuleSyntax": true,
"erasableSyntaxOnly": true,
"skipLibCheck": true,
"noUncheckedIndexedAccess": true,
"noUnusedLocals": true
},
"include": ["src", "mock", "vite.config.ts"]
}import react from "@vitejs/plugin-react";
import { defineConfig } from "vite";
import { mockApi } from "./mock/api.ts";
export default defineConfig({
plugins: [react(), mockApi()],
});import type { IncomingMessage, ServerResponse } from "node:http";
import type { Plugin } from "vite";
// A tiny in-memory API served by the Vite dev server – just enough to make the app real.
const menu = [
{ id: "ruskie", name: "Ruskie", description: "Potato, twaróg, fried onion", priceCents: 3200, vegetarian: true },
{ id: "meat", name: "Z mięsem", description: "Slow-cooked pork and beef", priceCents: 3600, vegetarian: false },
{ id: "cabbage", name: "Kapusta i grzyby", description: "Sauerkraut and forest mushrooms", priceCents: 3400, vegetarian: true },
{ id: "spinach", name: "Szpinak i feta", description: "Spinach, feta, garlic", priceCents: 3500, vegetarian: true },
{ id: "duck", name: "Z kaczką", description: "Duck with apple, cranberry sauce", priceCents: 4400, vegetarian: false },
];
type StoredOrder = { id: string; createdAt: number; customer: { name: string; address: string }; lines: unknown[] };
const orders = new Map<string, StoredOrder>();
// The status moves forward with time, so polling in the UI has something to show.
function statusOf(order: StoredOrder) {
const seconds = (Date.now() - order.createdAt) / 1000;
if (seconds < 10) return "placed";
if (seconds < 25) return "cooking";
if (seconds < 45) return "delivering";
return "delivered";
}
const send = (res: ServerResponse, status: number, body: unknown) => {
res.statusCode = status;
res.setHeader("Content-Type", "application/json");
setTimeout(() => res.end(JSON.stringify(body)), 300 + Math.random() * 400); // fake latency
};
async function readJson(req: IncomingMessage): Promise<unknown> {
let raw = "";
for await (const chunk of req) raw += chunk;
return JSON.parse(raw || "{}");
}
export function mockApi(): Plugin {
return {
name: "mock-api",
configureServer(server) {
server.middlewares.use("/api", async (req, res) => {
const url = req.url ?? "/";
if (req.method === "GET" && url === "/menu") return send(res, 200, menu);
if (req.method === "POST" && url === "/orders") {
const body = (await readJson(req)) as Omit<StoredOrder, "id" | "createdAt">;
const order = { ...body, id: String(1000 + orders.size + 1), createdAt: Date.now() };
orders.set(order.id, order);
return send(res, 201, { ...order, status: statusOf(order) });
}
const match = /^\/orders\/(\w+)$/.exec(url);
const order = match?.[1] ? orders.get(match[1]) : undefined;
if (req.method === "GET" && order) return send(res, 200, { ...order, status: statusOf(order) });
send(res, 404, { message: "Not found" });
});
},
};
}<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Pierogarnia</title>
</head>
<body>
<div id="root"></div>
<script type="module" src="/src/main.tsx"></script>
</body>
</html>:root { font-family: system-ui, sans-serif; color: #1f2328; background: #f6f7f9; }
body { margin: 0; }
a { color: #4263eb; }
.layout { max-width: 880px; margin: 0 auto; padding: 16px; }
.topbar { display: flex; gap: 16px; align-items: center; padding: 12px 0; border-bottom: 1px solid #dee2e6; }
.topbar .active { font-weight: 700; text-decoration: none; }
.progress { height: 3px; background: #4263eb; animation: grow 1s ease-out infinite; }
@keyframes grow { from { width: 0; } to { width: 100%; } }
.grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(240px, 1fr)); gap: 12px; }
.card { background: #fff; border: 1px solid #dee2e6; border-radius: 8px; padding: 12px; display: grid; gap: 8px; }
.field { display: grid; gap: 4px; margin-bottom: 12px; }
.field input, .field select, .field textarea { padding: 8px; border: 1px solid #ced4da; border-radius: 6px; font: inherit; }
.error { color: #c92a2a; font-size: 0.875rem; }
button { padding: 8px 12px; border-radius: 6px; border: 1px solid #4263eb; background: #4263eb; color: #fff; cursor: pointer; }
button:disabled { opacity: 0.6; cursor: wait; }Atrapa API to wtyczka Vite (configureServer), która obsługuje /api/menu i /api/orders 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 (/api/...) się nie zmieniają.
Krok 2. Komponenty i props
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:
- Czystość – ten sam input daje ten sam JSX. Żadnych zapytań HTTP ani zapisu do
localStoragew ciele komponentu. - Dane w dół, zdarzenia w górę –
MenuItemCarddostajeitemiquantity, a o kliknięciu informuje przezonAdd. Nie wie, gdzie jest koszyk. - Kompozycja przez
children– rodzic wstawia do karty dodatkową treść (np. etykietę „Vegetarian”), zamiast dokładać kolejne propsy typushowBadge.
Komponent prezentacyjny
const pln = new Intl.NumberFormat("pl-PL", { style: "currency", currency: "PLN" });
export const formatPrice = (cents: number) => pln.format(cents / 100);import type { ReactNode } from "react";
import { formatPrice } from "../../shared/format.ts";
import type { MenuItem } from "./api.ts";
interface MenuItemCardProps {
item: MenuItem;
quantity: number;
onAdd: (item: MenuItem) => void;
children?: ReactNode; // composition: the parent decides what extra content goes inside
}
// A presentational component: data in through props, events out through callbacks.
export function MenuItemCard({ item, quantity, onAdd, children }: MenuItemCardProps) {
return (
<article className="card">
<header style={{ display: "flex", justifyContent: "space-between", gap: 8 }}>
<strong>{item.name}</strong>
<span>{formatPrice(item.priceCents)}</span>
</header>
<p style={{ margin: 0, color: "#495057" }}>{item.description}</p>
{children}
<button type="button" onClick={() => onAdd(item)}>
{quantity > 0 ? `Add another (${quantity} in cart)` : "Add to cart"}
</button>
</article>
);
}Krok 3. Stan i hooki: useState, useReducer, useEffect, useMemo, useRef
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 useReducer + kontekst, a nie w TanStack Query.
| Hook | Do czego | Czego nim nie rób |
|---|---|---|
useState | prosta wartość lokalna: pole wyszukiwania, przełącznik | nie kopiuj do stanu propsów ani danych pochodnych |
useReducer | stan z kilkoma operacjami (dodaj, zmień ilość, wyczyść) | nie mieszaj w reducerze efektów ubocznych |
use(Context) | dostęp do wspólnego stanu bez przekazywania propsów | nie wrzucaj tam wszystkiego – każda zmiana renderuje konsumentów |
useEffect | synchronizacja z systemem zewnętrznym + sprzątanie | nie licz w nim danych pochodnych i nie pobieraj danych ręcznie |
useMemo | stabilna referencja lub kosztowne obliczenie | nie owijaj każdej linijki – mierz, zanim zoptymalizujesz |
useRef | uchwyt do elementu DOM, wartość bez renderowania (ID timera) | nie czytaj ref.current w trakcie renderowania |
Koszyk: reducer, kontekst i strona
import { createContext, use, useEffect, useMemo, useReducer, type ReactNode } from "react";
import { z } from "zod";
import type { MenuItem } from "../menu/api.ts";
const CartLineSchema = z.object({ id: z.string(), name: z.string(), priceCents: z.int(), quantity: z.int().positive() });
export type CartLine = z.infer<typeof CartLineSchema>;
type CartAction =
| { type: "add"; item: Pick<MenuItem, "id" | "name" | "priceCents"> }
| { type: "setQuantity"; id: string; quantity: number }
| { type: "clear" };
// A reducer is a pure function: (state, action) => new state. Easy to test, no React needed.
function cartReducer(lines: CartLine[], action: CartAction): CartLine[] {
switch (action.type) {
case "add": {
const existing = lines.find((l) => l.id === action.item.id);
return existing
? lines.map((l) => (l.id === action.item.id ? { ...l, quantity: l.quantity + 1 } : l))
: [...lines, { ...action.item, quantity: 1 }];
}
case "setQuantity":
return action.quantity <= 0
? lines.filter((l) => l.id !== action.id)
: lines.map((l) => (l.id === action.id ? { ...l, quantity: action.quantity } : l));
case "clear":
return [];
}
}
const STORAGE_KEY = "pierogi-cart";
// localStorage is external, untrusted data – validate it like an API response.
function loadCart(): CartLine[] {
try {
const parsed = z.array(CartLineSchema).safeParse(JSON.parse(localStorage.getItem(STORAGE_KEY) ?? "[]"));
return parsed.success ? parsed.data : [];
} catch {
return [];
}
}
type CartContextValue = {
lines: CartLine[];
count: number;
totalCents: number;
dispatch: (action: CartAction) => void;
};
const CartContext = createContext<CartContextValue | null>(null);
export function CartProvider({ children }: { children: ReactNode }) {
// Third argument = lazy initializer: localStorage is read once, not on every render.
const [lines, dispatch] = useReducer(cartReducer, [], loadCart);
// useEffect synchronises React state with an external system (here: localStorage).
useEffect(() => {
localStorage.setItem(STORAGE_KEY, JSON.stringify(lines));
}, [lines]);
// useMemo keeps the context value stable, so consumers re-render only when the cart changes.
const value = useMemo(
() => ({
lines,
dispatch,
count: lines.reduce((n, l) => n + l.quantity, 0),
totalCents: lines.reduce((sum, l) => sum + l.quantity * l.priceCents, 0),
}),
[lines],
);
// React 19: the context itself is the provider, and use() reads it.
return <CartContext value={value}>{children}</CartContext>;
}
export function useCart() {
const ctx = use(CartContext);
if (!ctx) throw new Error("useCart() must be used inside <CartProvider>");
return ctx;
}import { Link } from "react-router";
import { formatPrice } from "../../shared/format.ts";
import { useCart } from "./cart-context.tsx";
export function CartPage() {
const { lines, totalCents, dispatch } = useCart();
if (lines.length === 0) {
return (
<p>
<title>Cart · Pierogarnia</title>
Your cart is empty. <Link to="/">Browse the menu</Link>
</p>
);
}
return (
<section>
{/* React 19 hoists <title> into <head> – no effect or helmet library needed */}
<title>{`Cart (${lines.length}) · Pierogarnia`}</title>
<h1>Cart</h1>
<ul style={{ listStyle: "none", padding: 0, display: "grid", gap: 8 }}>
{lines.map((line) => (
<li key={line.id} className="card" style={{ gridTemplateColumns: "1fr auto auto", alignItems: "center" }}>
<span>{line.name}</span>
<input
type="number"
min={0}
max={50}
value={line.quantity}
aria-label={`Quantity of ${line.name}`}
onChange={(e) => dispatch({ type: "setQuantity", id: line.id, quantity: e.target.valueAsNumber || 0 })}
style={{ width: 64 }}
/>
<span>{formatPrice(line.priceCents * line.quantity)}</span>
</li>
))}
</ul>
<p>
<strong>Total: {formatPrice(totalCents)}</strong>
</p>
<Link to="/checkout">Go to checkout →</Link>
</section>
);
}Dalsza część artykułu dla zalogowanych
Załóż darmowe konto albo zaloguj się, aby przeczytać całość. W dalszej części:
- Krok 4. Pobieranie danych z TanStack Query
- Krok 5. Formularz: react-hook-form + Zod
- Krok 6. Routing w React Router 8
- Krok 7. Wydajność
- Typowe błędy
- Sprawdź się
- Co dalej