Poradnik · React · Obserwator
Zarządzanie stanem w React – Context, Zustand, Redux Toolkit i TanStack Query w praktyce
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.
„Którą bibliotekę do stanu wybrać?” to w React pytanie źle postawione. Najpierw trzeba ustalić, jaki to stan: 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.
Wymagania wstępne: Node.js 22.22+ (zalecany 24 lub 26 LTS), React na poziomie hooków useState/useEffect (patrz poradnik React), podstawy TypeScriptu.
- 4
- narzędzia – Context, Zustand, Redux Toolkit, TanStack Query
- 0,4 KB
- Zustand (gzip) – sam `create` – zmierzone esbuild
- 3
- playgroundy – Context vs Zustand, Redux Toolkit, optymistyczne UI
- 1
- zasada – najpierw rodzaj stanu, potem biblioteka
Pięć rodzajów stanu
Zanim sięgniesz po bibliotekę, nazwij stan. Ta tabela rozwiązuje większość sporów w code review:
| Rodzaj | Przykład w pierogarni | Gdzie trzymać |
|---|---|---|
| Stan serwera | menu, zamówienia, dostępność dań | TanStack Query (albo RTK Query, jeśli projekt już używa Reduxa) |
| Stan URL | filtr „wegetariańskie”, numer strony, ID zamówienia | parametry trasy i searchParams |
| Stan formularza | dane do wysyłki przed kliknięciem „Zamów” | react-hook-form |
| Stan lokalny | rozwinięta karta dania, tekst w wyszukiwarce | useState / useReducer w komponencie |
| Wspólny stan klienta | koszyk, motyw, zalogowany użytkownik | Context (rzadkie zmiany) albo Zustand / Redux Toolkit |
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.
Krok 1. Projekt
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
Projekt ma dwie strony startowe: index.html (koszyk w Zustand) i redux.html (ten sam koszyk w Redux Toolkit). Menu, motyw i atrapa API są wspólne – dzięki temu porównujesz tylko warstwę stanu.
Konfiguracja, strony i style
{
"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"
}
}{
"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"]
}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"] } },
});<!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><!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>: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; } }Krok 2. Context – do wartości, które zmieniają się rzadko
Context rozwiązuje problem przekazywania propsów przez wiele poziomów (prop drilling). Nie optymalizuje jednak renderowania: gdy zmienia się wartość providera, React renderuje każdy komponent, który ją czyta, nawet jeśli korzysta tylko z jej fragmentu. React.memo tu nie pomaga – odczyt kontekstu omija porównanie propsów.
Dlatego motyw dzielimy na dwa konteksty: wartość i funkcję zmiany. Przycisk, który tylko zmienia motyw, nie renderuje się przy jego zmianie, bo setTheme z useState ma stałą referencję. W React 19 kontekst renderujesz bezpośrednio jako provider (<ThemeContext value={…}>), a czytasz go hookiem use().
Atrapa API i motyw w Context
// 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);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>
);
}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 StrictMode jest wyłączony (ukryty plik /index.js), bo w trybie deweloperskim podwaja on renderowania i liczniki byłyby mylące.
Context vs Zustand – kto się renderuje? – Kliknij „+1” w obu panelach: Context renderuje wszystkie wiersze, Zustand z selektorem tylko zmieniony
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>
);
}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;
}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; }Dalsza część artykułu dla zalogowanych
Załóż darmowe konto albo zaloguj się, aby przeczytać całość. W dalszej części:
- Krok 3. Zustand – koszyk z selektorami i zapisem w localStorage
- Krok 4. Redux Toolkit – ten sam koszyk, jawne akcje
- Krok 5. TanStack Query – stan serwera i optymistyczne aktualizacje
- Porównanie
- Typowe błędy
- Sprawdź się
- Co dalej