Sub topic 9
Deciding Where State Lives
State placement decides how far a change spreads. If state sits too high, every edit touches unrelated code. If it sits too low, components copy each other's data and drift out of sync. This chapter gives you a way to choose the placement and the mistakes to watch for.
Prerequisites
This chapter assumes you know useState, useReducer, and context. It also assumes you have seen the feature-module layout from earlier chapters, with a public index.ts per feature, and that you have used a server-state library such as TanStack Query.
The placement rule
Put state in the lowest place that still lets every component that needs it reach it. Move it up only when a real second consumer appears.
The usual places, from lowest to highest, are:
| Location | Lifetime | Typical contents | Cost of sharing |
|---|---|---|---|
| Component (`useState`) | While the component is mounted | Input text, open or closed flags, hover state | None |
| Nearest common parent | While the parent is mounted | Selected tab, a filter shared by two siblings | Props passed down |
| Feature provider (context) | While the provider is mounted | Cart contents, a multi-step form draft | Context re-renders |
| URL | Survives reload and can be shared | Search text, page number, sort order | Parsing and validation |
| Server-state cache | Shared across the whole app | Orders, user profile, product lists | Cache keys |
| App-wide store | The whole session | Auth session, theme, feature flags | Every feature may depend on it |
A decision flow
Ask the questions below in order and stop at the first match.
The order matters. Server data comes first because copying it into client state is the most common source of bugs.
Start local, lift when needed
Keep state next to the component that uses it. A dropdown's open flag does not belong in a store, even if a store is already available.
Lift state only when two components need it. First move it to their nearest common parent and pass it as props. Passing props through one or two levels is fine. It keeps the data flow visible, and a search for the prop name finds every consumer.
Reach for context when props start passing through components that do not use them. Do this inside a feature first, not for the whole app.
Feature-level state with a provider
A cart is a good example. Several components in the cart feature read it, and nothing outside the feature should need to know how it is stored. Define the state, the reducer, and the provider inside the feature folder.
// src/features/cart/CartProvider.tsx
import {
createContext,
useContext,
useMemo,
useReducer,
type Dispatch,
type ReactNode,
} from "react";
export type CartItem = {
id: string;
name: string;
price: number;
quantity: number;
};
type Action =
| { type: "add"; item: CartItem }
| { type: "remove"; id: string };
function reducer(state: CartItem[], action: Action): CartItem[] {
switch (action.type) {
case "add": {
const existing = state.find((i) => i.id === action.item.id);
if (!existing) return [...state, action.item];
return state.map((i) =>
i.id === action.item.id
? { ...i, quantity: i.quantity + action.item.quantity }
: i
);
}
case "remove":
return state.filter((i) => i.id !== action.id);
}
}
type CartContextValue = {
items: CartItem[];
total: number;
dispatch: Dispatch<Action>;
};
const CartContext = createContext<CartContextValue | null>(null);
export function CartProvider({ children }: { children: ReactNode }) {
const [items, dispatch] = useReducer(reducer, []);
const value = useMemo(
() => ({
items,
total: items.reduce((sum, i) => sum + i.price * i.quantity, 0),
dispatch,
}),
[items]
);
return <CartContext.Provider value={value}>{children}</CartContext.Provider>;
}
export function useCart(): CartContextValue {
const ctx = useContext(CartContext);
if (!ctx) throw new Error("useCart must be used inside <CartProvider>");
return ctx;
}Three details are worth copying:
- The context object is not exported. Other code reaches it only through
useCart, so you can later replace the context with a store without changing any consumer. useCartthrows outside the provider. A missing provider then fails loudly instead of returningnulland crashing later.totalis computed fromitemsand is not stored separately.
Export CartProvider, useCart, and the CartItem type from the feature's index.ts. Mount the provider in src/app/, or at the root of the cart routes if only those routes need it. Mounting it lower also resets the cart state when the user leaves those routes, which may or may not be what you want.
Derive instead of duplicate
If a value can be computed from other state or props, compute it during render. Storing it creates a second copy that you must keep in sync.
import { useState } from "react";
type Product = { id: string; name: string; price: number };
export function ProductSearch({ products }: { products: Product[] }) {
const [query, setQuery] = useState("");
// Derived on every render. No second state variable and no effect.
const visible = products.filter((p) =>
p.name.toLowerCase().includes(query.toLowerCase())
);
return (
<div>
<input value={query} onChange={(e) => setQuery(e.target.value)} />
<ul>
{visible.map((p) => (
<li key={p.id}>{p.name}</li>
))}
</ul>
</div>
);
}The common mistake is a filtered state variable updated by an effect whenever query or products changes. That version renders once with stale data on every change and adds an effect that does nothing useful. If the computation is expensive, wrap it in useMemo and keep it derived.
Server state is a cache
Data from the API is not yours. The server owns it, and your app holds a possibly stale copy. Do not put that copy in useState, in context, or in a global store. Let the feature's hook own it, as in the data access chapter:
// src/features/orders/hooks/useOrders.ts
import { useQuery } from "@tanstack/react-query";
import { fetchOrders } from "../api";
export function useOrders(userId: string) {
return useQuery({
queryKey: ["orders", userId],
queryFn: () => fetchOrders(userId),
});
}Every component that calls useOrders("42") shares one cache entry. The library handles loading and error states, deduplicates requests, and refetches when data goes stale. You get shared state without writing a provider.
Keep two kinds of state separate. The server cache holds data. Client state holds choices the user made about how to view that data, such as which order is expanded. A selected order should be stored as an ID, not as a copy of the order object. The copy goes stale when the cache refetches, and the ID does not.
URL state
Anything a user might bookmark, share, or reload belongs in the URL. Examples are a search term, a page number, and a sort column. With React Router, useSearchParams gives you this state with the same shape as useState:
import { useSearchParams } from "react-router-dom";
export function OrderFilters() {
const [params, setParams] = useSearchParams();
const status = params.get("status") ?? "all";
return (
<select
value={status}
onChange={(e) => setParams({ status: e.target.value })}
>
<option value="all">All</option>
<option value="open">Open</option>
<option value="shipped">Shipped</option>
</select>
);
}URL values are strings and users can edit them. Validate or fall back to a default, as ?? "all" does here, before you pass them to an API call. Then pass status into useOrders-style hooks so it becomes part of the query key.
Common errors
- A global store for everything. Every feature then depends on the store, which undoes the boundaries you set up. Reserve app-wide state for things that are truly global, such as the auth session and the theme.
- One big context. All consumers re-render when any field in the value changes. Split contexts by how often they change, for example one for items and one for UI flags, or move the state to a store with selector subscriptions.
- Copying props into state.
useState(props.value)reads the prop only on the first render. Later changes are ignored. Use the prop directly, or make the component controlled. - Lifting too early. State moved up "just in case" makes unrelated components re-render and hides who owns it. Wait for the second consumer.
- Not lifting when needed. Two components that each keep their own copy of the same value drift apart. Give the value one owner.
- Reaching across features. If
ordersneeds data fromcart, import it throughcart'sindex.tshook. Do not import its context or reducer directly.
Exercise
A product page has a search box, a list of products fetched from /api/products, and a "compare" list where the user picks up to three products. The page should keep the search text after a reload and let users send the link to a colleague. Choose a location for each of the three pieces of state and give the reason for each.
Show answer
The product list is server state. Keep it in the server-state cache through a feature hook such as useProducts, so nothing copies it into useState. The search text goes in the URL search params, because it must survive a reload and be shareable. Pass it into the hook so it becomes part of the query key. The compare list is client state shared by the product cards and a compare panel. Store only the product IDs, not copies of the products, so the data stays fresh when the cache refetches. Keep the IDs in the nearest common parent, or in a small feature provider if the cards and the panel are far apart in the tree. Use a shared global store only if other features also need the list.