Advanced React State: When Local State Stops Fitting

Learn when React state needs a reducer and context, when Redux Toolkit helps, and why server data often belongs in a query cache instead.

published: reading time: 4 min read author: Geek Workbench updated: November 3, 2026
Quick Summary

Keep component-only values local, group related client updates in a reducer, and use context to share them when prop passing gets awkward. The example separates a local catalog filter and shared cart from server-fetched products in a query cache, then points to focused state and testing guides.

Advanced State Management in React: When Local State Stops Fitting

More structure does not automatically make state easier to manage. First ask who owns the value: one component, a feature shared by several components, or a remote service that can change outside the current screen.

Choose the state owner

Use this tree to pick a starting point. Context carries a feature’s state to descendants; the reducer or component still owns the updates.

flowchart TD
    A{Does the value come from a server?} -->|Yes| B[Keep it in a query cache]
    A -->|No| C{Does one component use it?}
    C -->|Yes| D[Keep it local with useState]
    C -->|No| E[Move it to the nearest shared owner]
    E --> F{Are the updates related?}
    F -->|Yes| G[Use a reducer]
    F -->|No| H[Use state and props]
    G --> I{Do many descendants need it?}
    H --> I
    I -->|Yes| J[Add context for that feature]
    I -->|No| K[Pass values and callbacks as props]

For client-owned state shared across unrelated features, consider Redux Toolkit. Keep server data in a query cache, whether you use TanStack Query or RTK Query. Do not copy remote records into a global store just because several screens use them. React’s guides explain how to choose a state structure and how reducers and context work together.

Refactor a catalog and cart

Imagine a first pass that kept fetched products, a filter string, and cart quantities in one reducer. Split them by ownership: the filter stays in the catalog component, cart updates move to a reducer shared through context, and product responses stay in a TanStack Query v5 cache. This example assumes fetchProducts returns validated Product[] and the app root is wrapped in QueryClientProvider.

import {
  createContext,
  useContext,
  useReducer,
  useState,
  type Dispatch,
  type ReactNode,
} from "react";
import { useQuery } from "@tanstack/react-query";
import { fetchProducts } from "./api/products";

interface Product {
  id: string;
  name: string;
}

type CartItems = Record<string, number>;
type CartAction = { type: "added"; productId: string };

function cartReducer(items: CartItems, action: CartAction): CartItems {
  switch (action.type) {
    case "added":
      return {
        ...items,
        [action.productId]: (items[action.productId] ?? 0) + 1,
      };
    default: {
      const exhaustive: never = action;
      return exhaustive;
    }
  }
}

const CartContext = createContext<{
  items: CartItems;
  dispatch: Dispatch<CartAction>;
} | null>(null);

function CartProvider({ children }: { children: ReactNode }) {
  const [items, dispatch] = useReducer(cartReducer, {});
  return (
    <CartContext.Provider value={{ items, dispatch }}>
      {children}
    </CartContext.Provider>
  );
}

function useCart() {
  const cart = useContext(CartContext);
  if (!cart) throw new Error("useCart must be used inside CartProvider");
  return cart;
}

function ProductList({ products }: { products: Product[] }) {
  const [filter, setFilter] = useState("");
  const { dispatch } = useCart();
  const visible = products.filter((product) =>
    product.name.toLowerCase().includes(filter.toLowerCase()),
  );

  return (
    <section>
      <label>
        Filter products
        <input
          value={filter}
          onChange={(event) => setFilter(event.currentTarget.value)}
        />
      </label>
      <ul>
        {visible.map((product) => (
          <li key={product.id}>
            {product.name}
            <button
              onClick={() => dispatch({ type: "added", productId: product.id })}
            >
              Add
            </button>
          </li>
        ))}
      </ul>
    </section>
  );
}

function CartSummary() {
  const { items } = useCart();
  const count = Object.values(items).reduce(
    (total, quantity) => total + quantity,
    0,
  );
  return <p>Items in cart: {count}</p>;
}

function CatalogPage() {
  const products = useQuery({
    queryKey: ["products"],
    queryFn: fetchProducts,
  });
  if (products.isPending) return <p>Loading products…</p>;
  if (products.isError) return <p>Could not load products.</p>;

  return (
    <>
      <ProductList products={products.data} />
      <CartSummary />
    </>
  );
}

export function Shop() {
  return (
    <CartProvider>
      <CatalogPage />
    </CartProvider>
  );
}

ProductList owns its temporary filter with useState. CartProvider owns quantity updates in a reducer. Context passes that state to both ProductList and CartSummary; the list dispatches additions, and the summary reads the count. The query cache owns the product response and its loading or error state. The cart stores product IDs and quantities, not a second copy of product records that could go stale.

Keep the boundary clear

A query cache does not replace authorization or validation. The server must check permissions, price, and availability when an order is submitted. Avoid logging full customer records. For API response validation, see Fetching and Typing API Data in React.

Further reading

Conclusion

After the refactor, test that filtering leaves the cart alone and adding a product updates both the list and the cart summary. Testing React Components and User Interactions covers behavior-first tests for those interactions.

Category

Related Posts

Accessible React UI: Semantics, Labels, and Keyboard Use

Build React interfaces with semantic controls, connected labels, visible keyboard focus, and status announcements through practical TypeScript examples.

#react #typescript #accessibility

Testing React Components and User Interactions

Write behavior-first React tests with accessible roles, realistic user events, and async assertions while avoiding brittle checks of implementation details.

#react #typescript #testing

Component Boundaries and React Project Structure

Organize React and TypeScript by feature, separate reusable UI from domain logic, and spot when a component has grown beyond one job.

#react #typescript #architecture