ReactEasy

What is global state?

Global state is data that many components across different parts of the app need to read or update, such as the logged-in user, theme, locale, feature flags, cart contents or notifications. It lives outside individual components, in context, a store (Zustand, Redux Toolkit, Jotai), the URL, or a server-state cache.

Kinds of "global" data

  1. Server state: data from APIs (products, profile). Best handled by TanStack Query, SWR, RTK Query, route loaders or Server Components, which add caching, refetching and deduplication.
  2. Client app state: cart, wizard progress, UI preferences, modals. Context or a store.
  3. URL state: filters, search terms, pagination, selected tab. Shareable and survives reloads.
  4. Form state: usually local to a form; form libraries manage it.
  5. Session data: the current user, often provided by an auth library.

Choosing a mechanism

  • Context: rarely changing values (theme, user, locale).
  • Zustand / Jotai: simple, hook-based stores with selective subscriptions.
  • Redux Toolkit: large apps needing strict patterns, middleware, DevTools time-travel, and RTK Query.
  • URL: anything users may bookmark or share.

Pitfalls

  • Putting everything in global state makes components harder to reuse and causes broad re-renders.
  • Duplicating server data in a client store leads to stale copies; prefer a server-state cache.
  • Keep state as local as possible and make it global only when several distant components truly share it.

Code example

tsx
1// A small global store with Zustand
2import { create } from "zustand";
3
4type CartItem = { id: string; name: string; qty: number };
5type CartState = {
6 items: CartItem[];
7 add: (item: Omit<CartItem, "qty">) => void;
8 clear: () => void;
9};
10
11export const useCart = create<CartState>((set) => ({
12 items: [],
13 add: (item) =>
14 set((s) => {
15 const existing = s.items.find((i) => i.id === item.id);
16 return existing
17 ? { items: s.items.map((i) => (i.id === item.id ? { ...i, qty: i.qty + 1 } : i)) }
18 : { items: [...s.items, { ...item, qty: 1 }] };
19 }),
20 clear: () => set({ items: [] }),
21}));
22
23// Any component, anywhere, subscribes to just the slice it needs
24export function CartBadge() {
25 const count = useCart((s) => s.items.reduce((n, i) => n + i.qty, 0));
26 return <span>🛒 {count}</span>;
27}

Practice this question

Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the React set.

Open in study app