{"id":"6b09aa835a5e2dbc3f20a4c1","slug":"react-state-management","title":"Zarządzanie stanem w React – Context, Zustand, Redux Toolkit i TanStack Query w praktyce","summary":"Kiedy wystarczy useState, kiedy Context, a kiedy Zustand, Redux Toolkit albo TanStack Query? Budujemy koszyk pierogarni w dwóch wersjach (Zustand i Redux Toolkit), menu z serwera z optymistycznymi aktualizacjami i porównujemy liczbę renderowań na żywo.","servedLang":"pl","availableLangs":["pl","en"],"topics":["react","observer","typescript"],"techs":["typescript","javascript"],"tags":["react-19","zustand","redux-toolkit","tanstack-query","context","optimistic-updates","selectors","state-management"],"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":20,"stats":{"views":1,"likes":0,"bookmarks":0,"comments":0},"publishedAt":"2026-11-27T16:06:27.377Z","updatedAt":"2026-11-27T16:08:48.056Z","requestedLang":"pl","theme":{"hero":"classic","heroMedia":null,"accent":"indigo","background":"grid","weaveResources":true,"toc":"right"},"seoDescription":"Zarządzanie stanem w React 19 – Context vs Zustand 5 vs Redux Toolkit 2 vs TanStack Query 5. Selektory, useShallow, persist, createSlice, listener middleware, optymistyczne aktualizacje, rozmiary bibliotek i drzewo decyzyjne.","wordCount":3858,"doc":{"type":"doc","content":[{"type":"paragraph","content":[{"type":"text","text":"„Którą bibliotekę do stanu wybrać?” to w React pytanie źle postawione. Najpierw trzeba ustalić, "},{"type":"text","text":"jaki to stan","marks":[{"type":"bold"}]},{"type":"text","text":": dane z serwera, wartość w URL, pola formularza, czy naprawdę wspólny stan interfejsu. Dopiero wtedy wybór narzędzia staje się prosty. W tym poradniku zbudujesz małą aplikację pierogarni, w której każde narzędzie robi to, w czym jest najlepsze, a na trzech działających przykładach zobaczysz różnice w renderowaniu i w przepływie danych."}]},{"type":"callout","attrs":{"variant":"info","title":"W skrócie"},"content":[{"type":"bulletList","content":[{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"Stan serwera ≠ stan klienta.","marks":[{"type":"bold"}]},{"type":"text","text":" Menu, zamówienia i profil użytkownika należą do cache'u TanStack Query. Zustand, Redux czy Context trzymają tylko to, co powstaje w przeglądarce: koszyk, motyw, otwarty panel."}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"Context to mechanizm przekazywania wartości, a nie menedżer stanu.","marks":[{"type":"bold"}]},{"type":"text","text":" Każda zmiana wartości renderuje wszystkich konsumentów. Nadaje się do danych zmieniających się rzadko (motyw, zalogowany użytkownik, zależności)."}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"Zustand i Redux Toolkit rozwiązują ten sam problem","marks":[{"type":"bold"}]},{"type":"text","text":" – subskrypcję fragmentu stanu przez selektor. Zustand jest minimalny, Redux Toolkit daje jawne akcje, middleware i ustandaryzowaną strukturę dla dużych zespołów."}]}]}]}]},{"type":"callout","attrs":{"variant":"tip","title":"Co zbudujesz"},"content":[{"type":"paragraph","content":[{"type":"text","text":"Aplikację „Pierogi” w Vite + React 19 + TypeScript: menu pobierane z atrapy serwera (TanStack Query, gwiazdka „ulubione” z optymistyczną aktualizacją i wycofaniem przy błędzie), koszyk w Zustand z zapisem w "},{"type":"text","text":"localStorage","marks":[{"type":"code"}]},{"type":"text","text":" oraz ten sam koszyk w Redux Toolkit pod adresem "},{"type":"text","text":"/redux.html","marks":[{"type":"code"}]},{"type":"text","text":" – z listener middleware, który ogłasza darmową dostawę. Motyw jasny/ciemny przechodzi przez Context. Kod (17 plików) pobierzesz jako ZIP ikoną przy artykule, a trzy przykłady uruchomisz od razu w przeglądarce."}]}]},{"type":"paragraph","content":[{"type":"text","text":"Wymagania wstępne:","marks":[{"type":"bold"}]},{"type":"text","text":" Node.js 22.22+ (zalecany 24 lub 26 LTS), React na poziomie hooków "},{"type":"text","text":"useState","marks":[{"type":"code"}]},{"type":"text","text":"/"},{"type":"text","text":"useEffect","marks":[{"type":"code"}]},{"type":"text","text":" (patrz "},{"type":"text","text":"poradnik React","marks":[{"type":"link","attrs":{"href":"/pl/articles/react"}}]},{"type":"text","text":"), podstawy TypeScriptu."}]},{"type":"stats","attrs":{"items":[{"value":"4","label":"narzędzia","hint":"Context, Zustand, Redux Toolkit, TanStack Query"},{"value":"0,4 KB","label":"Zustand (gzip)","hint":"sam `create` – zmierzone esbuild"},{"value":"3","label":"playgroundy","hint":"Context vs Zustand, Redux Toolkit, optymistyczne UI"},{"value":"1","label":"zasada","hint":"najpierw rodzaj stanu, potem biblioteka"}]}},{"type":"heading","attrs":{"level":2,"id":"piec-rodzajow-stanu"},"content":[{"type":"text","text":"Pięć rodzajów stanu"}]},{"type":"paragraph","content":[{"type":"text","text":"Zanim sięgniesz po bibliotekę, nazwij stan. Ta tabela rozwiązuje większość sporów w code review:"}]},{"type":"table","content":[{"type":"tableRow","content":[{"type":"tableHeader","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Rodzaj"}]}]},{"type":"tableHeader","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Przykład w pierogarni"}]}]},{"type":"tableHeader","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Gdzie trzymać"}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Stan serwera"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"menu, zamówienia, dostępność dań"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"TanStack Query (albo RTK Query, jeśli projekt już używa Reduxa)"}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Stan URL"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"filtr „wegetariańskie”, numer strony, ID zamówienia"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"parametry trasy i "},{"type":"text","text":"searchParams","marks":[{"type":"code"}]}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Stan formularza"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"dane do wysyłki przed kliknięciem „Zamów”"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"react-hook-form"}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Stan lokalny"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"rozwinięta karta dania, tekst w wyszukiwarce"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"useState","marks":[{"type":"code"}]},{"type":"text","text":" / "},{"type":"text","text":"useReducer","marks":[{"type":"code"}]},{"type":"text","text":" w komponencie"}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Wspólny stan klienta"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"koszyk, motyw, zalogowany użytkownik"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Context (rzadkie zmiany) albo Zustand / Redux Toolkit"}]}]}]}]},{"type":"paragraph","content":[{"type":"text","text":"Do „wspólnego stanu klienta” trafia zwykle zaskakująco mało rzeczy. Gdy usuniesz z globalnego store'a kopie danych z serwera i wartości, które powinny być w URL, często zostaje koszyk i kilka flag interfejsu."}]},{"type":"diagram","attrs":{"kind":"mermaid","code":"flowchart TD\n  Q1{\"Dane pochodzą z serwera?\"} -->|tak| TQ[\"TanStack Query<br/>cache, odświeżanie, ponowienia\"]\n  Q1 -->|nie| Q2{\"Da się je udostępnić linkiem?<br/>filtr, strona, ID\"}\n  Q2 -->|tak| URL[\"URL: trasa i searchParams\"]\n  Q2 -->|nie| Q3{\"To pola formularza<br/>przed wysyłką?\"}\n  Q3 -->|tak| RHF[\"react-hook-form\"]\n  Q3 -->|nie| Q4{\"Potrzebuje go więcej<br/>niż jedno poddrzewo?\"}\n  Q4 -->|nie| LOCAL[\"useState / useReducer\"]\n  Q4 -->|tak| Q5{\"Zmienia się często albo<br/>ma wielu konsumentów?\"}\n  Q5 -->|nie| CTX[\"Context: motyw, użytkownik, DI\"]\n  Q5 -->|tak| Q6{\"Duży zespół, złożone przepływy,<br/>potrzebny log akcji i middleware?\"}\n  Q6 -->|nie| Z[\"Zustand\"]\n  Q6 -->|tak| RTK[\"Redux Toolkit\"]","caption":"Drzewo decyzyjne: gdzie trzymać ten stan?"}},{"type":"heading","attrs":{"level":2,"id":"krok-1-projekt"},"content":[{"type":"text","text":"Krok 1. Projekt"}]},{"type":"codeBlock","attrs":{"language":"bash"},"content":[{"type":"text","text":"npm create vite@latest pierogi-state -- --template react-ts\ncd pierogi-state\nnpm install zustand @reduxjs/toolkit react-redux @tanstack/react-query\nnpm run dev"}]},{"type":"paragraph","content":[{"type":"text","text":"Projekt ma dwie strony startowe: "},{"type":"text","text":"index.html","marks":[{"type":"code"}]},{"type":"text","text":" (koszyk w Zustand) i "},{"type":"text","text":"redux.html","marks":[{"type":"code"}]},{"type":"text","text":" (ten sam koszyk w Redux Toolkit). Menu, motyw i atrapa API są wspólne – dzięki temu porównujesz tylko warstwę stanu."}]},{"type":"codeGroup","attrs":{"title":"Konfiguracja, strony i style"},"content":[{"type":"codeBlock","attrs":{"language":"json","filename":"package.json"},"content":[{"type":"text","text":"{\n  \"name\": \"pierogi-state\",\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    \"@reduxjs/toolkit\": \"^2.15.0\",\n    \"@tanstack/react-query\": \"^5.108.4\",\n    \"react\": \"^19.3.1\",\n    \"react-dom\": \"^19.3.1\",\n    \"react-redux\": \"^9.3.1\",\n    \"zustand\": \"^5.1.0\"\n  },\n  \"devDependencies\": {\n    \"@types/react\": \"^19.3.3\",\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\"],\n    \"jsx\": \"react-jsx\",\n    \"strict\": true,\n    \"noUncheckedIndexedAccess\": true,\n    \"verbatimModuleSyntax\": true,\n    \"allowImportingTsExtensions\": true,\n    \"noEmit\": true,\n    \"skipLibCheck\": true\n  },\n  \"include\": [\"src\", \"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\";\n\n// Two entry pages: index.html (Zustand cart) and redux.html (the same cart in Redux Toolkit).\nexport default defineConfig({\n  plugins: [react()],\n  build: { rollupOptions: { input: [\"index.html\", \"redux.html\"] } },\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>Pierogi – Zustand + TanStack Query</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":"html","filename":"redux.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>Pierogi – Redux Toolkit + TanStack Query</title>\n  </head>\n  <body>\n    <div id=\"root\"></div>\n    <script type=\"module\" src=\"/src/main-redux.tsx\"></script>\n  </body>\n</html>"}]},{"type":"codeBlock","attrs":{"language":"css","filename":"src/styles.css"},"content":[{"type":"text","text":":root { font-family: system-ui, sans-serif; }\nbody { margin: 0; }\n.app { min-height: 100vh; padding: 1rem 1.5rem; }\n.theme-light { background: #fff; color: #1a1a1a; }\n.theme-dark { background: #16181d; color: #e9ecef; }\nheader { display: flex; gap: 1rem; align-items: center; flex-wrap: wrap; }\n.layout { display: grid; grid-template-columns: 2fr 1fr; gap: 2rem; }\n.menu li { display: grid; grid-template-columns: auto 1fr auto auto; gap: .75rem; align-items: center; padding: .25rem 0; }\n.badge { font-size: .8em; padding: 0 .5em; border-radius: 1em; background: #4263eb; color: #fff; }\ninput[type=\"number\"] { width: 4rem; margin-left: .5rem; }\n@media (max-width: 640px) { .layout { grid-template-columns: 1fr; } }"}]}]},{"type":"heading","attrs":{"level":2,"id":"krok-2-context-do-wartosci-ktore-zmieniaja-sie-rzadko"},"content":[{"type":"text","text":"Krok 2. Context – do wartości, które zmieniają się rzadko"}]},{"type":"paragraph","content":[{"type":"text","text":"Context rozwiązuje problem przekazywania propsów przez wiele poziomów (prop drilling). Nie optymalizuje jednak renderowania: gdy zmienia się wartość providera, React renderuje "},{"type":"text","text":"każdy","marks":[{"type":"bold"}]},{"type":"text","text":" komponent, który ją czyta, nawet jeśli korzysta tylko z jej fragmentu. "},{"type":"text","text":"React.memo","marks":[{"type":"code"}]},{"type":"text","text":" tu nie pomaga – odczyt kontekstu omija porównanie propsów."}]},{"type":"paragraph","content":[{"type":"text","text":"Dlatego motyw dzielimy na dwa konteksty: wartość i funkcję zmiany. Przycisk, który tylko zmienia motyw, nie renderuje się przy jego zmianie, bo "},{"type":"text","text":"setTheme","marks":[{"type":"code"}]},{"type":"text","text":" z "},{"type":"text","text":"useState","marks":[{"type":"code"}]},{"type":"text","text":" ma stałą referencję. W React 19 kontekst renderujesz bezpośrednio jako provider ("},{"type":"text","text":"<ThemeContext value={…}>","marks":[{"type":"code"}]},{"type":"text","text":"), a czytasz go hookiem "},{"type":"text","text":"use()","marks":[{"type":"code"}]},{"type":"text","text":"."}]},{"type":"codeGroup","attrs":{"title":"Atrapa API i motyw w Context"},"content":[{"type":"codeBlock","attrs":{"language":"typescript","filename":"src/shared/fake-api.ts"},"content":[{"type":"text","text":"// In-memory \"server\" with latency, so loading states and optimistic updates are visible.\nexport type MenuItem = { id: string; name: string; priceCents: number; favorite: boolean };\n\nlet menu: MenuItem[] = [\n  { id: \"ruskie\", name: \"Ruskie (potato & cheese)\", priceCents: 2400, favorite: false },\n  { id: \"meat\", name: \"With meat\", priceCents: 2700, favorite: true },\n  { id: \"spinach\", name: \"Spinach & feta\", priceCents: 2600, favorite: false },\n  { id: \"berries\", name: \"Blueberries\", priceCents: 2200, favorite: false },\n];\n\nconst delay = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));\n\nexport async function fetchMenu(): Promise<MenuItem[]> {\n  await delay(500);\n  return structuredClone(menu);\n}\n\nexport async function setFavorite(id: string, favorite: boolean): Promise<MenuItem> {\n  await delay(700);\n  if (Math.random() < 0.2) throw new Error(\"Simulated 503 – try again\");\n  menu = menu.map((m) => (m.id === id ? { ...m, favorite } : m));\n  const updated = menu.find((m) => m.id === id);\n  if (!updated) throw new Error(`Unknown menu item: ${id}`);\n  return structuredClone(updated);\n}\n\nexport const formatPrice = (cents: number) =>\n  new Intl.NumberFormat(\"pl-PL\", { style: \"currency\", currency: \"PLN\" }).format(cents / 100);"}]},{"type":"codeBlock","attrs":{"language":"typescript","filename":"src/theme/theme-context.tsx"},"content":[{"type":"text","text":"import { createContext, use, useState, type ReactNode } from \"react\";\n\nexport type Theme = \"light\" | \"dark\";\n\n// Two contexts: components that only *change* the theme don't re-render when it changes.\nconst ThemeContext = createContext<Theme>(\"light\");\nconst SetThemeContext = createContext<(theme: Theme) => void>(() => {});\n\nexport function ThemeProvider({ children }: { children: ReactNode }) {\n  const [theme, setTheme] = useState<Theme>(() =>\n    window.matchMedia(\"(prefers-color-scheme: dark)\").matches ? \"dark\" : \"light\",\n  );\n  // setTheme from useState is stable, so SetThemeContext consumers never re-render.\n  return (\n    <SetThemeContext value={setTheme}>\n      <ThemeContext value={theme}>\n        <div className={`app theme-${theme}`}>{children}</div>\n      </ThemeContext>\n    </SetThemeContext>\n  );\n}\n\nexport const useTheme = () => use(ThemeContext);\nexport const useSetTheme = () => use(SetThemeContext);\n\nexport function ThemeToggle() {\n  const theme = useTheme();\n  const setTheme = useSetTheme();\n  return (\n    <button type=\"button\" onClick={() => setTheme(theme === \"dark\" ? \"light\" : \"dark\")}>\n      {theme === \"dark\" ? \"Light mode\" : \"Dark mode\"}\n    </button>\n  );\n}"}]}]},{"type":"paragraph","content":[{"type":"text","text":"Jak to wygląda w praktyce? Poniżej ten sam koszyk w dwóch wersjach. Kliknij „+1” kilka razy po obu stronach i porównaj liczniki renderowań. W tych przykładach "},{"type":"text","text":"StrictMode","marks":[{"type":"code"}]},{"type":"text","text":" jest wyłączony (ukryty plik "},{"type":"text","text":"/index.js","marks":[{"type":"code"}]},{"type":"text","text":"), bo w trybie deweloperskim podwaja on renderowania i liczniki byłyby mylące."}]},{"type":"playground","attrs":{"template":"react","files":{"/App.js":{"code":"import { createContext, useContext, useState } from \"react\";\nimport { create } from \"zustand\";\nimport { useRenderCount } from \"./useRenderCount\";\n\nconst MENU = [\n  { id: \"ruskie\", name: \"Ruskie\", price: 24 },\n  { id: \"meat\", name: \"With meat\", price: 27 },\n  { id: \"spinach\", name: \"Spinach & feta\", price: 26 },\n];\n\n/* ---------- A: one Context with the whole cart ---------- */\nconst CartContext = createContext(null);\n\nfunction ContextCart({ children }) {\n  const [lines, setLines] = useState({});\n  const add = (id) => setLines((l) => ({ ...l, [id]: (l[id] ?? 0) + 1 }));\n  return <CartContext value={{ lines, add }}>{children}</CartContext>;\n}\n\nfunction ContextRow({ item }) {\n  const { lines, add } = useContext(CartContext); // subscribes to EVERYTHING\n  const n = useRenderCount();\n  return (\n    <li>\n      <button onClick={() => add(item.id)}>+1</button> {item.name} × {lines[item.id] ?? 0}\n      <span className=\"renders\">renders: {n}</span>\n    </li>\n  );\n}\n\nfunction ContextTotal() {\n  const { lines } = useContext(CartContext);\n  const n = useRenderCount();\n  const total = MENU.reduce((sum, m) => sum + (lines[m.id] ?? 0) * m.price, 0);\n  return <p>Total: {total} zł <span className=\"renders\">renders: {n}</span></p>;\n}\n\n/* ---------- B: Zustand store + selectors ---------- */\nconst useCart = create((set) => ({\n  lines: {},\n  add: (id) => set((s) => ({ lines: { ...s.lines, [id]: (s.lines[id] ?? 0) + 1 } })),\n}));\n\nfunction ZustandRow({ item }) {\n  const qty = useCart((s) => s.lines[item.id] ?? 0); // subscribes to ONE number\n  const add = useCart((s) => s.add);\n  const n = useRenderCount();\n  return (\n    <li>\n      <button onClick={() => add(item.id)}>+1</button> {item.name} × {qty}\n      <span className=\"renders\">renders: {n}</span>\n    </li>\n  );\n}\n\nfunction ZustandTotal() {\n  const total = useCart((s) => MENU.reduce((sum, m) => sum + (s.lines[m.id] ?? 0) * m.price, 0));\n  const n = useRenderCount();\n  return <p>Total: {total} zł <span className=\"renders\">renders: {n}</span></p>;\n}\n\nexport default function App() {\n  return (\n    <div className=\"grid\">\n      <section>\n        <h3>A. React Context</h3>\n        <ContextCart>\n          <ul>{MENU.map((m) => <ContextRow key={m.id} item={m} />)}</ul>\n          <ContextTotal />\n        </ContextCart>\n      </section>\n      <section>\n        <h3>B. Zustand + selectors</h3>\n        <ul>{MENU.map((m) => <ZustandRow key={m.id} item={m} />)}</ul>\n        <ZustandTotal />\n      </section>\n      <p className=\"hint\">\n        Click “+1” a few times in both panels and compare the counters.\n      </p>\n    </div>\n  );\n}","active":true},"/useRenderCount.js":{"code":"import { useRef } from \"react\";\n\n// Demo helper: counts how many times the component function ran.\n// (Mutating a ref during render is not something to do in real code –\n// use the React DevTools Profiler there.)\nexport function useRenderCount() {\n  const renders = useRef(0);\n  renders.current += 1;\n  return renders.current;\n}"},"/styles.css":{"code":"body { font-family: system-ui, sans-serif; margin: 0; padding: 12px; color: #1f2328; }\n.grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(240px, 1fr)); gap: 16px; }\nsection { border: 1px solid #d0d7de; border-radius: 8px; padding: 8px 12px; }\nh3 { margin: 4px 0 8px; font-size: 16px; }\nul { list-style: none; padding: 0; margin: 0; }\nli { padding: 4px 0; }\nbutton { margin-right: 6px; cursor: pointer; }\n.renders { float: right; font: 12px ui-monospace, monospace; background: #fff3bf; padding: 1px 6px; border-radius: 4px; }\n.hint { grid-column: 1 / -1; font-size: 13px; color: #57606a; }"},"/index.js":{"code":"import { createRoot } from \"react-dom/client\";\nimport \"./styles.css\";\nimport App from \"./App\";\n\n// No <StrictMode> on purpose: in development it renders every component twice,\n// which would double the render counters shown in this demo.\ncreateRoot(document.getElementById(\"root\")).render(<App />);","hidden":true}},"dependencies":{"zustand":"^5.1.0"},"layout":"preview","height":560,"title":"Context vs Zustand – kto się renderuje?","caption":"Kliknij „+1” w obu panelach: Context renderuje wszystkie wiersze, Zustand z selektorem tylko zmieniony","editable":true}}]},"toc":[{"id":"piec-rodzajow-stanu","text":"Pięć rodzajów stanu","level":2,"locked":false},{"id":"krok-1-projekt","text":"Krok 1. Projekt","level":2,"locked":false},{"id":"krok-2-context-do-wartosci-ktore-zmieniaja-sie-rzadko","text":"Krok 2. Context – do wartości, które zmieniają się rzadko","level":2,"locked":false},{"id":"krok-3-zustand-koszyk-z-selektorami-i-zapisem-w-localstorage","text":"Krok 3. Zustand – koszyk z selektorami i zapisem w localStorage","level":2,"locked":true},{"id":"krok-4-redux-toolkit-ten-sam-koszyk-jawne-akcje","text":"Krok 4. Redux Toolkit – ten sam koszyk, jawne akcje","level":2,"locked":true},{"id":"krok-5-tanstack-query-stan-serwera-i-optymistyczne-aktualizacje","text":"Krok 5. TanStack Query – stan serwera i optymistyczne aktualizacje","level":2,"locked":true},{"id":"porownanie","text":"Porównanie","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":62,"visibleBlocks":20,"resources":[{"id":"6b0857cc3c96f2d34d0b4cdf","type":"video","provider":"youtube","url":"https://www.youtube.com/watch?v=p4kQNyfqGtE","embedUrl":"https://www.youtube-nocookie.com/embed/p4kQNyfqGtE","title":"Max Stoiber – Rethinking frontend architectures with data layers – Kongres Next.js 2024","description":"After speaking with thousands of engineers at hundreds of companies, we noticed a peculiar pattern in how the fastest-moving companies manage the interface between backend and frontend: they all have a data layer. Let's dive into what data layers are, why these companies can move faster by having…","author":"Type of Web","thumbnailUrl":"https://i.ytimg.com/vi/p4kQNyfqGtE/hqdefault.jpg","durationSec":null,"lang":"pl","topics":[],"techs":["javascript"],"tags":[],"price":"free","featured":false,"featuredOrder":0,"packageName":null,"source":"youtube-rss","publishedAt":"2024-03-14T13:32:27.000Z","popularity":36,"verifiedAt":"2026-11-26T11:14:27.000Z","curated":false,"addedBy":"6b0857a15a2625e44ecaabe6","createdAt":"2026-11-26T16:01:15.892Z","updatedAt":"2026-11-26T16:01:15.892Z"},{"id":"6b0857ca3c96f2d34d0b4bc7","type":"video","provider":"youtube","url":"https://www.youtube.com/watch?v=mOIVFF57RIU","embedUrl":"https://www.youtube-nocookie.com/embed/mOIVFF57RIU","title":"Frontend bez czekania na backend – Optimistic UI | Tomasz Stolarczyk","description":"Jeśli interesują Cię decyzje, które pozwalają wdrażać zmiany bez ryzyka i bez czekania aż „wszystko się policzy”, to koniecznie zajrzyj tu: https://devbites.pl/kursy/feature-flags/?utm_source=youtube&utm_medium=social&utm_campaign=YT-dvstl-channel&utm_content=stolarczyk_2_desc - to dokładnie ten…","author":"devstyle","thumbnailUrl":"https://i.ytimg.com/vi/mOIVFF57RIU/hqdefault.jpg","durationSec":null,"lang":"pl","topics":[],"techs":["javascript"],"tags":[],"price":"free","featured":false,"featuredOrder":0,"packageName":null,"source":"youtube-rss","publishedAt":"2026-01-25T18:01:00.000Z","popularity":47,"verifiedAt":"2026-11-26T11:14:13.000Z","curated":false,"addedBy":"6b0857a15a2625e44ecaabe6","createdAt":"2026-11-26T16:01:12.872Z","updatedAt":"2026-11-26T16:01:12.872Z"},{"id":"6b0857b13c96f2d34d0b32a8","type":"article","provider":"devto","url":"https://dev.to/nicolalc/event-driven-architecture-for-clean-react-component-communication-fph","embedUrl":null,"title":"Event-Driven Architecture for Clean React Component Communication","description":"Are you tired of the endless tangle of props drilling and callback chains in your React applications?...","author":"Nicola","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%2F1x6le3uym4iwhcg4bt4j.png","durationSec":null,"lang":"en","topics":["event-driven-architecture"],"techs":["javascript"],"tags":["software-architecture","react","webdev","architecture","javascript"],"price":"free","featured":false,"featuredOrder":0,"packageName":null,"source":"devto","publishedAt":"2024-12-04T12:46:40.000Z","popularity":73,"verifiedAt":"2026-11-26T10:52:09.000Z","curated":false,"addedBy":"6b0857a15a2625e44ecaabe6","createdAt":"2026-11-26T16:00:49.541Z","updatedAt":"2026-11-26T16:00:49.541Z"},{"id":"6b0857b23c96f2d34d0b358c","type":"repo","provider":"github","url":"https://github.com/bespoyasov/frontend-clean-architecture","embedUrl":null,"title":"bespoyasov/frontend-clean-architecture","description":"React + TypeScript app built using the clean architecture principles in a more functional way.","author":"bespoyasov","thumbnailUrl":"https://opengraph.githubassets.com/1/bespoyasov/frontend-clean-architecture","durationSec":null,"lang":"en","topics":["clean-architecture","onion-architecture","layered-architecture"],"techs":["typescript"],"tags":["adapters","application","clean-architecture","domain","functional","layered-architecture","software-architecture","onion-architecture"],"price":"free","featured":false,"featuredOrder":0,"packageName":null,"source":"github","publishedAt":"2021-06-07T10:34:43.000Z","popularity":66,"verifiedAt":"2026-11-26T10:57:56.000Z","curated":false,"addedBy":"6b0857a15a2625e44ecaabe6","createdAt":"2026-11-26T16:00:50.215Z","updatedAt":"2026-11-26T16:00:50.215Z"},{"id":"6b0857bb3c96f2d34d0b3f6a","type":"podcast","provider":"apple-podcasts","url":"https://podcasts.apple.com/us/podcast/mastering-event-sourcing-with-redux-and-back-end/id1364741140?i=1000674733395","embedUrl":"https://embed.podcasts.apple.com/us/podcast/id1364741140?i=1000674733395","title":"Mastering Event Sourcing with Redux and Back-End Insights - RRU 271","description":"In this episode, they dive deep into the world of event sourcing with special guest, Luis Galeas, CEO and founder of Ambar. Lucas Paganini, along with Chris and Peter explore the intricacies of event sourcing, comparing front-end implementations using Redux and back-end approaches, and…","author":"React Round Up","thumbnailUrl":"https://is1-ssl.mzstatic.com/image/thumb/Podcasts211/v4/d2/e6/f6/d2e6f6aa-7493-cf21-16c9-60fcf714a821/mza_1953266210085483906.jpg/600x600bb.jpg","durationSec":2610,"lang":"en","topics":["event-sourcing"],"techs":["javascript"],"tags":["podcast","system-design","software-architecture"],"price":"free","featured":false,"featuredOrder":0,"packageName":null,"source":"itunes","publishedAt":"2024-10-24T10:00:00.000Z","popularity":49,"verifiedAt":"2026-11-26T10:58:53.000Z","curated":false,"addedBy":"6b0857a15a2625e44ecaabe6","createdAt":"2026-11-26T16:00:57.868Z","updatedAt":"2026-11-26T16:00:57.868Z"}],"challenges":[{"id":"6b093ddebd4755deb67ee06b","slug":"event-emitter","title":"Własny EventEmitter","summary":"Piszemy uproszczony odpowiednik `EventEmitter` z Node.js – on, once, off, emit i specjalne zdarzenie `error`. Wzorzec Obserwator w praktyce, z pułapkami modyfikacji listy w trakcie emisji.","servedLang":"pl","availableLangs":["pl","en"],"kind":"code","category":"algorithms","status":"published","difficulty":"easy","topics":["observer"],"techs":["typescript","javascript","python"],"tags":["design","events","observer","node","javascript"],"languages":["typescript","javascript","python"],"questionCount":null,"xp":10,"stats":{"attempts":0,"solves":0,"solutions":0,"comments":0},"solveRate":null,"publishedAt":"2026-11-27T08:22:54.007Z"},{"id":"6b0857af5a2625e44ecaad13","slug":"design-patterns-basics-quiz","title":"Wzorce projektowe – podstawy","summary":"Sześć pytań o klasyczne wzorce GoF: grupy, przeznaczenie i różnice.","servedLang":"pl","availableLangs":["pl","en"],"kind":"quiz","category":null,"status":"published","difficulty":"easy","topics":["builder","adapter","strategy","decorator","composite","facade","observer"],"techs":["general"],"tags":["quiz","gof","basics"],"languages":[],"questionCount":6,"xp":10,"stats":{"attempts":1,"solves":1,"solutions":0,"comments":0},"solveRate":100,"publishedAt":"2026-11-26T16:00:47.960Z"},{"id":"6b0857af5a2625e44ecaad10","slug":"order-observer","title":"Obserwator zamówień","summary":"Zamówienie powiadamia subskrybentów o zmianie statusu; subskrypcję da się anulować, a dziennik audytu zapisuje przejścia.","servedLang":"pl","availableLangs":["pl","en"],"kind":"code","category":null,"status":"published","difficulty":"medium","topics":["observer"],"techs":["dotnet","typescript"],"tags":["observer","events","behavioral"],"languages":["csharp","typescript"],"questionCount":null,"xp":20,"stats":{"attempts":1,"solves":1,"solutions":1,"comments":0},"solveRate":100,"publishedAt":"2026-11-26T16:00:47.864Z"}],"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":104,"skills":[{"key":"typescript","title":"TypeScript","level":5,"levelLabel":"Autorytet","articles":90},{"key":"dotnet","title":".NET","level":5,"levelLabel":"Autorytet","articles":61},{"key":"python","title":"Python","level":5,"levelLabel":"Autorytet","articles":59},{"key":"java","title":"Java","level":5,"levelLabel":"Autorytet","articles":46}]}}