State management: what goes where
State management starts with one question: what type of state is this? Local, shared, global client, server and URL state each have a natural home, and putting them in the right place removes extra re-renders, lost filters and stale API data.
45.1 Why is it used?
- Putting every state in one Context means every consumer re-renders when any value changes: a menu toggle re-renders the product list.
- A category kept in Context resets to All on refresh or when the link is shared.
- API data copied into state by hand has no caching, no refetch and can go stale.
React (JSX)
function AppProvider({ children }) { const [products, setProducts] = useState([]); const [category, setCategory] = useState("all"); const [menuOpen, setMenuOpen] = useState(false); useEffect(() => { fetch("/api/products") .then((res) => res.json()).then(setProducts); }, []); const value = { products, category, menuOpen, setCategory, setMenuOpen }; return ( <AppContext value={value}>{children}</AppContext> );}Output
-- initial --[button] MenuShoes, Watch, Bag -- after clicking Menu --[button] MenuHome · OrdersShoes, Watch, BagConsole: ProductList re-render- Step 1
1.Menu toggle changes the Context value
- Step 2
2.All consumers re-render (ProductList too)
- Step 3
3.Refresh or share: category back to All
- Step 4
4.Products copied from API: no cache, no refetch
Fix: give each state its own home
45.2 The 5 types of state
| Type | Belongs to | Examples | Home |
|---|---|---|---|
| Local | One component | Menu open, input value | useState |
| Shared | A few components | Selected item used by siblings | Lift up to common parent |
| Global client | The whole app | Theme, logged in user, cart | Context or a store (Zustand, Redux) |
| Server | Data from an API | Products, orders, reviews | Query library (TanStack Query) |
| URL | The address bar | Filters, sort, page number | useSearchParams |
45.3 Local state: the menu belongs to Header
- Only Header needs menuOpen, so it is useState inside Header, toggled with an updater function.
- Clicking Menu re-renders only Header; ProductList is untouched.
- Rule: keep state only as high as it needs to be; if two siblings need it, lift it to their common parent.
React (JSX)
function Header() { const [menuOpen, setMenuOpen] = useState(false); return ( <header> <button onClick={() => setMenuOpen((o) => !o)}> Menu </button> {menuOpen && <nav>Home · Orders</nav>} </header> );}Output
-- initial --[button] Menu -- after clicking Menu --[button] MenuHome · Orders45.4 URL state: the category
- The user expects the same filter after refresh, back button or a shared link, so it is URL state.
- useSearchParams reads category with "all" as the default; setParams writes ?category=shoes.
- Sharing the link opens the page directly with the Shoes filter.
React (JSX)
import { useSearchParams } from "react-router";function CategoryFilter() { const [params, setParams] = useSearchParams(); const category = params.get("category") ?? "all"; return ( <select value={category} onChange={(e) => setParams({ category: e.target.value })} > <option value="all">All</option> <option value="shoes">Shoes</option> </select> );}Output
-- initial --Category: AllURL: /products -- after selecting Shoes --Category: ShoesURL: /products?category=shoes45.5 Server state: the products
- The real data lives on the server; we only hold a copy that can go stale.
- useQuery takes a queryKey and a queryFn and handles caching, loading and refetching.
- Two components with the same key send only one request (details in the TanStack Query videos).
React (JSX)
import { useQuery } from "@tanstack/react-query"; const fetchProducts = () => fetch("/api/products").then((res) => res.json()); function ProductList() { const { data, isPending } = useQuery({ queryKey: ["products"], queryFn: fetchProducts, }); if (isPending) return <p>Loading...</p>; return <p>{data.join(", ")}</p>;}Output
-- first render --Loading... -- after the fetch --Shoes, Watch, Bag45.6 Where should state live: decision flow
- Step 1
1.Came from an API? Server state: query library
- Step 2
2.Must survive refresh or a shared link? URL state
- Step 3
3.Only one component needs it? useState
- Step 4
4.Many components need it? Lift up, then Context or a store
Check in this order
45.7 Checkpoint: which state is misplaced?
- Product page with qty, sort, reviews and zoomOpen in useState: which two are wrong?
- Answer: sort (URL state, should survive a shared link) and reviews (from an API, so server state).
- qty and zoomOpen are UI state of this page, so useState is correct.
React (JSX)
function ProductPage() { const [qty, setQty] = useState(1); const [sort, setSort] = useState("price"); const [reviews, setReviews] = useState([]); const [zoomOpen, setZoomOpen] = useState(false); // reviews come from the API in useEffect // ...rest of the UI}45.8 Common mistakes
- Copying useQuery data into Context or Redux with a useEffect: two sources of truth, and the store can show old data after a refetch.
- Fix: every component that needs products calls useQuery itself; the same key means the same cache.
- Storing derived values (cart total) as separate state instead of calculating during render.
- Putting form fields in a global store; they are local state.
React (JSX)
function ProductList() { const { data } = useQuery(productsQuery); const { setProducts } = use(AppContext); useEffect(() => { if (data) setProducts(data); }, [data, setProducts]); // other components read from context}React (JSX)
// any component that needs productsfunction ProductList() { const { data } = useQuery(productsQuery); // same queryKey = same cache}45.9 When to use which
- Start simple: useState, then lift up, then Context, a store only when needed.
- Myth: every app needs Redux from day one. After moving server state to a query library and filters to the URL, little global state is left.
- What remains (theme, user, cart) is fine in Context or one small store.
45.10 Interview tips
- First identify the type of state, then pick the tool.
- Server data: TanStack Query; shareable filters: the URL; one component: useState.
- Truly app-wide client state: Context or a store like Zustand or Redux.
- Say it: most "global state" is actually server state.
- Do not store derived values; compute them during render.