Polski

Tutorial · React · Observer

State management in React – Context, Zustand, Redux Toolkit and TanStack Query in practice

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.

By · · 21 min read

"Which state library should I pick?" is the wrong question in React. First you have to figure out what kind of state it is: 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.

Prerequisites: Node.js 22.22+ (24 or 26 LTS recommended), React at the level of useState/useEffect (see the React tutorial), TypeScript basics.

4
tools – Context, Zustand, Redux Toolkit, TanStack Query
0.4 KB
Zustand (gzip) – just `create` – measured with esbuild
3
playgrounds – Context vs Zustand, Redux Toolkit, optimistic UI
1
rule – state kind first, library second

Five kinds of state

Before reaching for a library, name the state. This table settles most code review debates:

KindDumpling shop exampleWhere it lives
Server statemenu, orders, dish availabilityTanStack Query (or RTK Query if the project already uses Redux)
URL state"vegetarian" filter, page number, order IDroute params and searchParams
Form statedelivery details before "Order" is clickedreact-hook-form
Local stateexpanded dish card, search box textuseState / useReducer in the component
Shared client statecart, theme, signed-in userContext (rare changes) or Zustand / Redux Toolkit

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.

Diagram: Decision tree: where should this state live?

Step 1. The project

npm create vite@latest pierogi-state -- --template react-ts
cd pierogi-state
npm install zustand @reduxjs/toolkit react-redux @tanstack/react-query
npm run dev

The project has two entry pages: index.html (the cart in Zustand) and redux.html (the same cart in Redux Toolkit). The menu, theme and fake API are shared, so you compare only the state layer.

Configuration, pages and styles

package.json
{
  "name": "pierogi-state",
  "private": true,
  "version": "0.1.0",
  "type": "module",
  "scripts": {
    "dev": "vite",
    "build": "tsc --noEmit && vite build",
    "preview": "vite preview"
  },
  "dependencies": {
    "@reduxjs/toolkit": "^2.15.0",
    "@tanstack/react-query": "^5.108.4",
    "react": "^19.3.1",
    "react-dom": "^19.3.1",
    "react-redux": "^9.3.1",
    "zustand": "^5.1.0"
  },
  "devDependencies": {
    "@types/react": "^19.3.3",
    "@types/react-dom": "^19.3.0",
    "@vitejs/plugin-react": "^6.3.0",
    "typescript": "~7.0.2",
    "vite": "^8.4.0"
  }
}
tsconfig.json
{
  "compilerOptions": {
    "target": "es2023",
    "lib": ["ES2023", "DOM", "DOM.Iterable"],
    "module": "esnext",
    "moduleResolution": "bundler",
    "types": ["vite/client"],
    "jsx": "react-jsx",
    "strict": true,
    "noUncheckedIndexedAccess": true,
    "verbatimModuleSyntax": true,
    "allowImportingTsExtensions": true,
    "noEmit": true,
    "skipLibCheck": true
  },
  "include": ["src", "vite.config.ts"]
}
vite.config.ts
import react from "@vitejs/plugin-react";
import { defineConfig } from "vite";

// Two entry pages: index.html (Zustand cart) and redux.html (the same cart in Redux Toolkit).
export default defineConfig({
  plugins: [react()],
  build: { rollupOptions: { input: ["index.html", "redux.html"] } },
});
index.html
<!doctype html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Pierogi – Zustand + TanStack Query</title>
  </head>
  <body>
    <div id="root"></div>
    <script type="module" src="/src/main.tsx"></script>
  </body>
</html>
redux.html
<!doctype html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Pierogi – Redux Toolkit + TanStack Query</title>
  </head>
  <body>
    <div id="root"></div>
    <script type="module" src="/src/main-redux.tsx"></script>
  </body>
</html>
src/styles.css
:root { font-family: system-ui, sans-serif; }
body { margin: 0; }
.app { min-height: 100vh; padding: 1rem 1.5rem; }
.theme-light { background: #fff; color: #1a1a1a; }
.theme-dark { background: #16181d; color: #e9ecef; }
header { display: flex; gap: 1rem; align-items: center; flex-wrap: wrap; }
.layout { display: grid; grid-template-columns: 2fr 1fr; gap: 2rem; }
.menu li { display: grid; grid-template-columns: auto 1fr auto auto; gap: .75rem; align-items: center; padding: .25rem 0; }
.badge { font-size: .8em; padding: 0 .5em; border-radius: 1em; background: #4263eb; color: #fff; }
input[type="number"] { width: 4rem; margin-left: .5rem; }
@media (max-width: 640px) { .layout { grid-template-columns: 1fr; } }

Step 2. Context – for values that rarely change

Context solves passing props through many levels (prop drilling). It does not optimise rendering, though: when the provider's value changes, React re-renders every component that reads it, even if it uses only part of it. React.memo does not help here – reading a context bypasses the props comparison.

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 setTheme from useState has a stable identity. In React 19 you render a context directly as a provider (<ThemeContext value={…}>) and read it with the use() hook.

Fake API and theme in Context

src/shared/fake-api.ts
// In-memory "server" with latency, so loading states and optimistic updates are visible.
export type MenuItem = { id: string; name: string; priceCents: number; favorite: boolean };

let menu: MenuItem[] = [
  { id: "ruskie", name: "Ruskie (potato & cheese)", priceCents: 2400, favorite: false },
  { id: "meat", name: "With meat", priceCents: 2700, favorite: true },
  { id: "spinach", name: "Spinach & feta", priceCents: 2600, favorite: false },
  { id: "berries", name: "Blueberries", priceCents: 2200, favorite: false },
];

const delay = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));

export async function fetchMenu(): Promise<MenuItem[]> {
  await delay(500);
  return structuredClone(menu);
}

export async function setFavorite(id: string, favorite: boolean): Promise<MenuItem> {
  await delay(700);
  if (Math.random() < 0.2) throw new Error("Simulated 503 – try again");
  menu = menu.map((m) => (m.id === id ? { ...m, favorite } : m));
  const updated = menu.find((m) => m.id === id);
  if (!updated) throw new Error(`Unknown menu item: ${id}`);
  return structuredClone(updated);
}

export const formatPrice = (cents: number) =>
  new Intl.NumberFormat("pl-PL", { style: "currency", currency: "PLN" }).format(cents / 100);
src/theme/theme-context.tsx
import { createContext, use, useState, type ReactNode } from "react";

export type Theme = "light" | "dark";

// Two contexts: components that only *change* the theme don't re-render when it changes.
const ThemeContext = createContext<Theme>("light");
const SetThemeContext = createContext<(theme: Theme) => void>(() => {});

export function ThemeProvider({ children }: { children: ReactNode }) {
  const [theme, setTheme] = useState<Theme>(() =>
    window.matchMedia("(prefers-color-scheme: dark)").matches ? "dark" : "light",
  );
  // setTheme from useState is stable, so SetThemeContext consumers never re-render.
  return (
    <SetThemeContext value={setTheme}>
      <ThemeContext value={theme}>
        <div className={`app theme-${theme}`}>{children}</div>
      </ThemeContext>
    </SetThemeContext>
  );
}

export const useTheme = () => use(ThemeContext);
export const useSetTheme = () => use(SetThemeContext);

export function ThemeToggle() {
  const theme = useTheme();
  const setTheme = useSetTheme();
  return (
    <button type="button" onClick={() => setTheme(theme === "dark" ? "light" : "dark")}>
      {theme === "dark" ? "Light mode" : "Dark mode"}
    </button>
  );
}

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. StrictMode is turned off in these examples (the hidden /index.js file), because in development it doubles renders and the counters would be misleading.

Context vs Zustand – who re-renders? – Click “+1” in both panels: Context re-renders every row, Zustand with a selector only the changed one

/App.js
import { createContext, useContext, useState } from "react";
import { create } from "zustand";
import { useRenderCount } from "./useRenderCount";

const MENU = [
  { id: "ruskie", name: "Ruskie", price: 24 },
  { id: "meat", name: "With meat", price: 27 },
  { id: "spinach", name: "Spinach & feta", price: 26 },
];

/* ---------- A: one Context with the whole cart ---------- */
const CartContext = createContext(null);

function ContextCart({ children }) {
  const [lines, setLines] = useState({});
  const add = (id) => setLines((l) => ({ ...l, [id]: (l[id] ?? 0) + 1 }));
  return <CartContext value={{ lines, add }}>{children}</CartContext>;
}

function ContextRow({ item }) {
  const { lines, add } = useContext(CartContext); // subscribes to EVERYTHING
  const n = useRenderCount();
  return (
    <li>
      <button onClick={() => add(item.id)}>+1</button> {item.name} × {lines[item.id] ?? 0}
      <span className="renders">renders: {n}</span>
    </li>
  );
}

function ContextTotal() {
  const { lines } = useContext(CartContext);
  const n = useRenderCount();
  const total = MENU.reduce((sum, m) => sum + (lines[m.id] ?? 0) * m.price, 0);
  return <p>Total: {total} zł <span className="renders">renders: {n}</span></p>;
}

/* ---------- B: Zustand store + selectors ---------- */
const useCart = create((set) => ({
  lines: {},
  add: (id) => set((s) => ({ lines: { ...s.lines, [id]: (s.lines[id] ?? 0) + 1 } })),
}));

function ZustandRow({ item }) {
  const qty = useCart((s) => s.lines[item.id] ?? 0); // subscribes to ONE number
  const add = useCart((s) => s.add);
  const n = useRenderCount();
  return (
    <li>
      <button onClick={() => add(item.id)}>+1</button> {item.name} × {qty}
      <span className="renders">renders: {n}</span>
    </li>
  );
}

function ZustandTotal() {
  const total = useCart((s) => MENU.reduce((sum, m) => sum + (s.lines[m.id] ?? 0) * m.price, 0));
  const n = useRenderCount();
  return <p>Total: {total} zł <span className="renders">renders: {n}</span></p>;
}

export default function App() {
  return (
    <div className="grid">
      <section>
        <h3>A. React Context</h3>
        <ContextCart>
          <ul>{MENU.map((m) => <ContextRow key={m.id} item={m} />)}</ul>
          <ContextTotal />
        </ContextCart>
      </section>
      <section>
        <h3>B. Zustand + selectors</h3>
        <ul>{MENU.map((m) => <ZustandRow key={m.id} item={m} />)}</ul>
        <ZustandTotal />
      </section>
      <p className="hint">
        Click “+1” a few times in both panels and compare the counters.
      </p>
    </div>
  );
}
/useRenderCount.js
import { useRef } from "react";

// Demo helper: counts how many times the component function ran.
// (Mutating a ref during render is not something to do in real code –
// use the React DevTools Profiler there.)
export function useRenderCount() {
  const renders = useRef(0);
  renders.current += 1;
  return renders.current;
}
/styles.css
body { font-family: system-ui, sans-serif; margin: 0; padding: 12px; color: #1f2328; }
.grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(240px, 1fr)); gap: 16px; }
section { border: 1px solid #d0d7de; border-radius: 8px; padding: 8px 12px; }
h3 { margin: 4px 0 8px; font-size: 16px; }
ul { list-style: none; padding: 0; margin: 0; }
li { padding: 4px 0; }
button { margin-right: 6px; cursor: pointer; }
.renders { float: right; font: 12px ui-monospace, monospace; background: #fff3bf; padding: 1px 6px; border-radius: 4px; }
.hint { grid-column: 1 / -1; font-size: 13px; color: #57606a; }

In the Context version every click re-renders all three rows and the total, because they all read the same { lines, add } object. In Zustand a row subscribes to a single number (s.lines[item.id]), 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.

The rest of this article is for members

Create a free account or sign in to read it all. Still ahead:

  • Step 3. Zustand – a cart with selectors and localStorage persistence
  • Step 4. Redux Toolkit – the same cart, explicit actions
  • Step 5. TanStack Query – server state and optimistic updates
  • Comparison
  • Common mistakes
  • Check yourself
  • What next

Create a free account · Sign in