{"id":"6b09aa835a5e2dbc3f20a4c1","slug":"react-state-management","title":"State management in React – Context, Zustand, Redux Toolkit and TanStack Query in practice","summary":"When is useState enough, when Context, and when Zustand, Redux Toolkit or TanStack Query? We build a dumpling shop cart in two versions (Zustand and Redux Toolkit), a server-backed menu with optimistic updates, and compare render counts live.","servedLang":"en","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":21,"stats":{"views":2,"likes":0,"bookmarks":0,"comments":0},"publishedAt":"2026-11-27T16:06:27.377Z","updatedAt":"2026-11-27T17:23:38.609Z","requestedLang":"en","theme":{"hero":"classic","heroMedia":null,"accent":"indigo","background":"grid","weaveResources":true,"toc":"right"},"seoDescription":"State management in React 19 – Context vs Zustand 5 vs Redux Toolkit 2 vs TanStack Query 5. Selectors, useShallow, persist, createSlice, listener middleware, optimistic updates, library sizes and a decision tree.","wordCount":4134,"doc":{"type":"doc","content":[{"type":"paragraph","content":[{"type":"text","text":"\"Which state library should I pick?\" is the wrong question in React. First you have to figure out "},{"type":"text","text":"what kind of state it is","marks":[{"type":"bold"}]},{"type":"text","text":": server data, a value in the URL, form fields, or genuinely shared UI state. Once you know that, choosing the tool becomes easy. In this tutorial you will build a small dumpling shop (pierogi) app where every tool does what it is best at, and three live examples will show you the differences in rendering and data flow."}]},{"type":"callout","attrs":{"variant":"info","title":"In short"},"content":[{"type":"bulletList","content":[{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"Server state ≠ client state.","marks":[{"type":"bold"}]},{"type":"text","text":" The menu, orders and user profile belong in the TanStack Query cache. Zustand, Redux or Context hold only what is born in the browser: the cart, the theme, an open panel."}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"Context is a way to pass values down, not a state manager.","marks":[{"type":"bold"}]},{"type":"text","text":" Every change of its value re-renders all consumers. It fits data that rarely changes (theme, signed-in user, dependencies)."}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"Zustand and Redux Toolkit solve the same problem","marks":[{"type":"bold"}]},{"type":"text","text":" – subscribing to a slice of state through a selector. Zustand is minimal; Redux Toolkit gives you explicit actions, middleware and a standard structure for large teams."}]}]}]}]},{"type":"callout","attrs":{"variant":"tip","title":"What you will build"},"content":[{"type":"paragraph","content":[{"type":"text","text":"A \"Pierogi\" app in Vite + React 19 + TypeScript: a menu fetched from a fake server (TanStack Query, a \"favorite\" star with an optimistic update and rollback on error), a cart in Zustand persisted to "},{"type":"text","text":"localStorage","marks":[{"type":"code"}]},{"type":"text","text":", and the same cart in Redux Toolkit at "},{"type":"text","text":"/redux.html","marks":[{"type":"code"}]},{"type":"text","text":" – with a listener middleware that announces free delivery. The light/dark theme flows through Context. You can download the code (17 files) as a ZIP using the icon next to the article, and run the three examples right in your browser."}]}]},{"type":"paragraph","content":[{"type":"text","text":"Prerequisites:","marks":[{"type":"bold"}]},{"type":"text","text":" Node.js 22.22+ (24 or 26 LTS recommended), React at the level of "},{"type":"text","text":"useState","marks":[{"type":"code"}]},{"type":"text","text":"/"},{"type":"text","text":"useEffect","marks":[{"type":"code"}]},{"type":"text","text":" (see the "},{"type":"text","text":"React tutorial","marks":[{"type":"link","attrs":{"href":"/en/articles/react"}}]},{"type":"text","text":"), TypeScript basics."}]},{"type":"stats","attrs":{"items":[{"value":"4","label":"tools","hint":"Context, Zustand, Redux Toolkit, TanStack Query"},{"value":"0.4 KB","label":"Zustand (gzip)","hint":"just `create` – measured with esbuild"},{"value":"3","label":"playgrounds","hint":"Context vs Zustand, Redux Toolkit, optimistic UI"},{"value":"1","label":"rule","hint":"state kind first, library second"}]}},{"type":"heading","attrs":{"level":2,"id":"five-kinds-of-state"},"content":[{"type":"text","text":"Five kinds of state"}]},{"type":"paragraph","content":[{"type":"text","text":"Before reaching for a library, name the state. This table settles most code review debates:"}]},{"type":"table","content":[{"type":"tableRow","content":[{"type":"tableHeader","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Kind"}]}]},{"type":"tableHeader","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Dumpling shop example"}]}]},{"type":"tableHeader","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Where it lives"}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Server state"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"menu, orders, dish availability"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"TanStack Query (or RTK Query if the project already uses Redux)"}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"URL state"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"\"vegetarian\" filter, page number, order ID"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"route params and "},{"type":"text","text":"searchParams","marks":[{"type":"code"}]}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Form state"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"delivery details before \"Order\" is clicked"}]}]},{"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":"Local state"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"expanded dish card, search box text"}]}]},{"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":" in the component"}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Shared client state"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"cart, theme, signed-in user"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Context (rare changes) or Zustand / Redux Toolkit"}]}]}]}]},{"type":"paragraph","content":[{"type":"text","text":"Surprisingly little ends up as \"shared client state\". Once you remove copies of server data and values that belong in the URL from the global store, you are often left with the cart and a few UI flags."}]},{"type":"diagram","attrs":{"kind":"mermaid","code":"flowchart TD\n  Q1{\"Does the data come from a server?\"} -->|yes| TQ[\"TanStack Query<br/>cache, refetching, retries\"]\n  Q1 -->|no| Q2{\"Can it be shared with a link?<br/>filter, page, ID\"}\n  Q2 -->|yes| URL[\"URL: route and searchParams\"]\n  Q2 -->|no| Q3{\"Is it form fields<br/>before submit?\"}\n  Q3 -->|yes| RHF[\"react-hook-form\"]\n  Q3 -->|no| Q4{\"Needed by more than<br/>one subtree?\"}\n  Q4 -->|no| LOCAL[\"useState / useReducer\"]\n  Q4 -->|yes| Q5{\"Changes often or has<br/>many consumers?\"}\n  Q5 -->|no| CTX[\"Context: theme, user, DI\"]\n  Q5 -->|yes| Q6{\"Large team, complex flows,<br/>need an action log and middleware?\"}\n  Q6 -->|no| Z[\"Zustand\"]\n  Q6 -->|yes| RTK[\"Redux Toolkit\"]","caption":"Decision tree: where should this state live?"}},{"type":"heading","attrs":{"level":2,"id":"step-1-the-project"},"content":[{"type":"text","text":"Step 1. The project"}]},{"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":"The project has two entry pages: "},{"type":"text","text":"index.html","marks":[{"type":"code"}]},{"type":"text","text":" (the cart in Zustand) and "},{"type":"text","text":"redux.html","marks":[{"type":"code"}]},{"type":"text","text":" (the same cart in Redux Toolkit). The menu, theme and fake API are shared, so you compare only the state layer."}]},{"type":"codeGroup","attrs":{"title":"Configuration, pages and styles"},"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":"step-2-context-for-values-that-rarely-change"},"content":[{"type":"text","text":"Step 2. Context – for values that rarely change"}]},{"type":"paragraph","content":[{"type":"text","text":"Context solves passing props through many levels (prop drilling). It does not optimise rendering, though: when the provider's value changes, React re-renders "},{"type":"text","text":"every","marks":[{"type":"bold"}]},{"type":"text","text":" component that reads it, even if it uses only part of it. "},{"type":"text","text":"React.memo","marks":[{"type":"code"}]},{"type":"text","text":" does not help here – reading a context bypasses the props comparison."}]},{"type":"paragraph","content":[{"type":"text","text":"That is why we split the theme into two contexts: the value and the setter. A button that only changes the theme does not re-render when the theme changes, because "},{"type":"text","text":"setTheme","marks":[{"type":"code"}]},{"type":"text","text":" from "},{"type":"text","text":"useState","marks":[{"type":"code"}]},{"type":"text","text":" has a stable identity. In React 19 you render a context directly as a provider ("},{"type":"text","text":"<ThemeContext value={…}>","marks":[{"type":"code"}]},{"type":"text","text":") and read it with the "},{"type":"text","text":"use()","marks":[{"type":"code"}]},{"type":"text","text":" hook."}]},{"type":"codeGroup","attrs":{"title":"Fake API and theme in 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":"What does it look like in practice? Below is the same cart in two versions. Click \"+1\" a few times on both sides and compare the render counters. "},{"type":"text","text":"StrictMode","marks":[{"type":"code"}]},{"type":"text","text":" is turned off in these examples (the hidden "},{"type":"text","text":"/index.js","marks":[{"type":"code"}]},{"type":"text","text":" file), because in development it doubles renders and the counters would be misleading."}]},{"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 – who re-renders?","caption":"Click “+1” in both panels: Context re-renders every row, Zustand with a selector only the changed one","editable":true}},{"type":"paragraph","content":[{"type":"text","text":"In the Context version every click re-renders all three rows and the total, because they all read the same "},{"type":"text","text":"{ lines, add }","marks":[{"type":"code"}]},{"type":"text","text":" object. In Zustand a row subscribes to a single number ("},{"type":"text","text":"s.lines[item.id]","marks":[{"type":"code"}]},{"type":"text","text":"), so only the changed row and the total re-render. With three rows it does not matter; with a list of 300 dishes and a field that changes on every keystroke, it does."}]}]},"toc":[{"id":"five-kinds-of-state","text":"Five kinds of state","level":2,"locked":false},{"id":"step-1-the-project","text":"Step 1. The project","level":2,"locked":false},{"id":"step-2-context-for-values-that-rarely-change","text":"Step 2. Context – for values that rarely change","level":2,"locked":false},{"id":"step-3-zustand-a-cart-with-selectors-and-localstorage-persistence","text":"Step 3. Zustand – a cart with selectors and localStorage persistence","level":2,"locked":true},{"id":"step-4-redux-toolkit-the-same-cart-explicit-actions","text":"Step 4. Redux Toolkit – the same cart, explicit actions","level":2,"locked":true},{"id":"step-5-tanstack-query-server-state-and-optimistic-updates","text":"Step 5. TanStack Query – server state and optimistic updates","level":2,"locked":true},{"id":"comparison","text":"Comparison","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":62,"visibleBlocks":21,"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":"Your own EventEmitter","summary":"Write a simplified version of Node.js `EventEmitter` – on, once, off, emit and the special `error` event. The Observer pattern in practice, with the traps of modifying the list during emission.","servedLang":"en","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":"Design patterns – basics","summary":"Six questions about classic GoF patterns: groups, intent and differences.","servedLang":"en","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":"Order observer","summary":"An order notifies subscribers when its status changes; subscriptions can be cancelled and an audit log records transitions.","servedLang":"en","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":"Authority","articles":90},{"key":"dotnet","title":".NET","level":5,"levelLabel":"Authority","articles":61},{"key":"python","title":"Python","level":5,"levelLabel":"Authority","articles":59},{"key":"java","title":"Java","level":5,"levelLabel":"Authority","articles":46}]}}