Managing State
Most state bugs are not caused by the wrong library. They are caused by state living in the wrong place, being duplicated, or being treated as if all state were the same kind of state. The first decision is not “Redux or Zustand”, it is “what kind of state is this and who owns it”.
The 60-second answer
Section titled “The 60-second answer”“State belongs as close as possible to where it is used. useState covers component-local concerns;
when two siblings need the same value, lift it to their closest common parent and pass it down. When
it must cross many layers, use context — but context is dependency injection for values, not a state
manager, and every consumer re-renders when the value changes. When transitions become numerous and
interrelated, consolidate them into a reducer so the update logic is testable outside React. Server
data is a different category: cached, refetchable, shared, so it belongs in a query library, not a
client store. Most apps need local state, one context for cross-cutting concerns and a query library;
a global store only when client state is genuinely app-wide.”
Classify the state first
Section titled “Classify the state first”| Kind | Examples | Where it belongs |
|---|---|---|
| Local UI | Open/closed, hover, draft input | useState in the component |
| Lifted UI | Selected tab shared by siblings | Common parent |
| Cross-cutting | Theme, locale, authenticated user | Context |
| Complex transitions | Multi-step form, editor document | useReducer (+ context) |
| Server data | Lists, records, anything from an API | Query library |
| URL state | Filters, pagination, search | The URL |
| Persistent | Preferences, draft recovery | localStorage or the server |
Two questions settle most cases: can this be computed instead of stored? and must it survive a reload? If it can be computed, derive it during render. If it should survive a reload, the URL or the server is the better home.
Local state and lifting
Section titled “Local state and lifting”Store what the user did, not every visual consequence. An accordion needs one openId, not a
boolean per panel: fewer states, and two panels cannot be open by accident.
const [openId, setOpenId] = useState<string | null>(null);
<button aria-expanded={openId === item.id} onClick={() => setOpenId(openId === item.id ? null : item.id)}> {item.title}</button>{openId === item.id && <p>{item.body}</p>}When two siblings must change together, move the state to their closest common parent and pass the
value down with a callback up. To reset a child’s state when its identity changes, change its key
rather than writing a reset effect: <Chat key={contact.id} contact={contact} />.
Context
Section titled “Context”const ThemeContext = createContext<{ theme: Theme; toggle: () => void } | null>(null);
export function ThemeProvider({ children }: { children: ReactNode }) { const [theme, setTheme] = useState<Theme>('light'); const value = useMemo(() => ({ theme, toggle: () => setTheme((t) => (t === 'light' ? 'dark' : 'light')), }), [theme]); return <ThemeContext.Provider value={value}>{children}</ThemeContext.Provider>;}
export function useTheme() { const ctx = useContext(ThemeContext); if (!ctx) throw new Error('useTheme must be used inside ThemeProvider'); return ctx;}The custom hook with the null check turns a runtime undefined into a clear error and keeps the
context object private to the module. Every useContext consumer re-renders when the value changes,
so split contexts by update frequency and memoise the value.
Reducers
Section titled “Reducers”When one event updates several fields, or the transitions are the interesting part, move the logic
into a pure reducer: useReducer(cartReducer, []). The reducer switches on action.type, returns a
new state, and the action union documents every legal transition — assertNever(action) in the
default branch makes a missed case a compile error.
The payoff is testability: the reducer is a pure function you can unit-test without rendering.
Combine it with context — state in one provider, dispatch in another, since dispatch is
stable — to avoid prop drilling without re-rendering everything on each change.
Server state is not client state
Section titled “Server state is not client state”Server data is owned elsewhere, can be stale, can be refetched, and is shared between screens. A client store that copies it must reimplement caching, deduplication, invalidation and retries.
Libraries in this category (TanStack Query, SWR) give you caching, background refetching, request
deduplication and optimistic updates: useQuery caches by key and exposes isPending, error and
data; useMutation invalidates the affected keys on success. Next.js extends the idea to the
server with fetch caching and revalidation; see
Next.js.
Redux, Flux and Zustand
Section titled “Redux, Flux and Zustand”| Flux | Redux | Zustand | |
|---|---|---|---|
| What it is | Architectural pattern | Library implementing unidirectional flow | Small store library |
| Stores | Multiple | Single | Multiple allowed |
| Updates | Dispatcher → store | Pure reducers, immutable state | set with a partial |
| Boilerplate | Medium | High without Redux Toolkit | Low |
| Best fit | Historical context | Large apps, auditable transitions | Small to medium global state |
Flux is the pattern: actions go to a dispatcher, stores update, views re-render. Redux is one
implementation with a single store and pure reducers; modern Redux means Redux Toolkit
(createSlice, Immer-backed updates, RTK Query for server data). Choose a store when state is
genuinely global, changes frequently and is read by unrelated parts of the tree — not because “the
app might grow”.
Follow-up questions
Section titled “Follow-up questions”- Why does context re-render every consumer, and how do you limit that?
- When would you keep filter state in the URL instead of
useState? - What does Redux give you that
useReducerplus context does not? - How do optimistic updates work, and how do you roll one back?
Common traps
Section titled “Common traps”- One global store for everything. It couples unrelated features and makes every change risky.
- Copying server data into a client store. You now own cache invalidation.
- Storing derived values. They drift from their source.
- Context with a new object every render. The provider re-renders all consumers; memoise it.
- Mutating state in place.
pushdoes not change the reference, so React does not re-render.