---
title: State & data fetching
summary: Where data lives on the frontend, how it gets there, and how to keep it fresh.
section: frontend
phase: build
order: 2
last_reviewed: 2026-11-20
---

# State & data fetching

Most frontend bugs are state bugs: stale data, duplicate sources of truth, race conditions. The fix is to decide where each piece of state lives before anything gets built.

## You'll be able to
- Classify state and pick the right home for each kind
- Choose between server rendering, client fetching and caching libraries
- Recognize over-engineered state management

## The mental model
There are four kinds of state, and each has a natural home:

| Kind | Example | Home |
|---|---|---|
| **Server state** | List of orders | The database. On the client, it's a *cache* (Server Components, TanStack Query, SWR) |
| **URL state** | Current page, filters, selected tab | The URL (search params) |
| **Local UI state** | Is this modal open? | Component state (`useState`) |
| **Global client state** | Theme, shopping cart before checkout | Context or a small store (Zustand) |

Most apps need far less "global state" than agents give them.

## Key concepts
- **Fetching on the server vs the client:** Server Components and loaders fetch before HTML is sent, which is fast and SEO-friendly. Client fetching happens after the page loads.
- **Caching & revalidation:** How long fetched data is considered fresh, and how to invalidate it after a mutation.
- **Mutations:** Writes (form submits, Server Actions, POST requests). After a mutation, revalidate or update the cache.
- **Optimistic updates:** Show the change immediately and roll it back if the server rejects it.
- **Race conditions:** An older response arriving after a newer one. Libraries handle this; hand-rolled `useEffect` fetching often doesn't.
- **Hydration:** The client "taking over" server-rendered HTML. A hydration mismatch means the server and client rendered different output.

## Decisions you make (not the agent)
| Decision | Sensible default | Choose otherwise when… |
|---|---|---|
| Server data | Fetch in Server Components / loaders | Highly interactive client views → TanStack Query |
| Filters, pagination | URL search params | Ephemeral UI only |
| Global store | None until it hurts; then Zustand | Large existing Redux app |
| Writes | Server Actions / form actions + revalidate | Separate API backend → TanStack Query mutations |

## What good output looks like

- Server data is fetched on the server, or through a library that handles caching, rather than hand-rolled in effects
- Filters, sort and pagination live in the URL, so refresh and sharing work
- Each piece of data has one home, and nothing is copied into a second place
- After a write, the affected data is revalidated or updated
- Loading, error and cancellation are handled

## Red flags
- `useEffect` + `fetch` + `useState` everywhere, with no error handling or cancellation
- The same data copied into a global store *and* a component's state
- Redux added to a five-page app
- Filters that disappear on refresh because they weren't kept in the URL
- **Common agent mistakes:** several booleans (`isLoading`, `isError`, `isSuccess`) that can contradict each other instead of one `status`; storing a copy of an object when only its ID is needed; computing a derived value in an effect and storing it in state instead of calculating it while rendering

## Worked example

**Task:** Add a status filter to the orders list.

You prompt: *"Add a status filter to the orders page."* The agent adds a `useState` for the filter and a `useEffect` that fetches orders whenever it changes.

**What a good result contains:** the filter value in the URL (`?status=shipped`), the orders fetched on the server or through a data library for that URL, and a list that always matches the current filter.

**The wrong turn:** if someone switches filters quickly, responses can arrive out of order, so the screen shows results for a filter that is no longer selected. React's documentation describes exactly this race condition in effect-based fetching, and the fix it gives is a cleanup step that ignores stale responses, though it recommends the mechanisms built into frameworks. The filter also disappears when the page is refreshed, because it only exists in component state.

**How review catches it:** switch filters quickly with the network throttled, then refresh the page and share the URL with yourself in another tab. Both break. Ask the agent where each piece of state lives and what kind it is. Then re-prompt: filters in the URL, data fetched for that URL, no effect-based fetching.

## Sample prompts
```text
Refactor the orders page so that: orders are fetched on the server, filters
(status, date range) and pagination live in URL search params, and creating an
order uses a Server Action that revalidates the list. Remove the useEffect-based
fetching and the unused Zustand slice. Keep the existing UI.
```
*Why it works:* Every kind of state gets a named home, and the removal list stops old and new approaches from coexisting.

```text
Audit this app's state management. For each piece of state, tell me what kind it
is (server/URL/local/global), where it currently lives, and where it should live.
Flag duplicated sources of truth.
```
*Why it works:* Classifying before changing anything shows you the problems first, and "duplicated sources of truth" is the bug behind most stale-data reports.

### Audit effect-based fetching
```text
Find every useEffect in this codebase that fetches data. For each, tell me: whether it ignores stale responses (cleanup), how it handles errors and loading, whether the data could instead be fetched on the server or through the data library we already use, and whether the same data also lives somewhere else. Don't change anything yet.
```
*Why it works:* It turns "state is messy" into a list of specific effects with a verdict each.

### Debug stale data after a save
```text
After I save an order, the list still shows the old data until I refresh. Trace what happens after the write: where the list's data comes from, how it is cached, and what should refresh it. Explain the cause, then fix it by revalidating or updating that data. Show the before and after behaviour.
```
*Why it works:* Stale data after a mutation almost always means nothing told the cache to refresh. Naming that sends the agent to the right place.

### Explain where each piece of state lives
```text
For the change you just made, list every piece of state it uses, and for each: its kind (server, URL, local or global), where it lives, what the single source of truth is, and what happens when the user refreshes the page. Point out anything that exists in two places.
```
*Why it works:* The refresh question exposes the state that isn't where it should be. Verify the answer in the code.

## Check your understanding

```quiz
Q: Where should a list's filters and pagination live?
- [ ] In a global store
- [x] In the URL search params
- [ ] In a component's local state
> Why: URL state survives refresh, can be shared and works with the back button. Local state is lost, and a global store adds machinery you don't need.

---

Q: A user switches filters quickly and the screen shows results for an older filter. What is this called, and how is it handled?
- [ ] Hydration mismatch; reload the page
- [x] A race condition; ignore stale responses with a cleanup step, or use a framework or library that handles it
- [ ] Caching; clear the cache
> Why: Responses can arrive out of order. React's documentation recommends cleanup to drop stale responses, and frameworks provide better built-in mechanisms.

---

Q: A component has isLoading, isError and isSuccess booleans. What is the better structure?
- [ ] Add more booleans so every case is covered
- [x] One status value that can only be in one valid state at a time
- [ ] Put them in a global store
> Why: Separate flags can contradict each other (loading and error at once). A single status makes impossible states impossible.
```

## Checklist

- [ ] Each piece of state is classified (server, URL, local, global) and lives in one place
- [ ] Filters and pagination are in the URL
- [ ] No effect-based fetching without cleanup and error handling
- [ ] After every write, the affected data is revalidated or updated
- [ ] Loading, empty and error states exist for fetched data

## Go deeper
- [TanStack Query: Overview](https://tanstack.com/query/latest/docs/framework/react/overview)
- [Next.js: Data fetching](https://nextjs.org/docs/app/building-your-application/data-fetching)
- [Next.js: Revalidating](https://nextjs.org/docs/app/getting-started/revalidating): refreshing cached data, including after a mutation
- [React: You Might Not Need an Effect](https://react.dev/learn/you-might-not-need-an-effect): fetching in effects and race conditions
- [React: Choosing the State Structure](https://react.dev/learn/choosing-the-state-structure): avoiding duplicated and contradictory state
- [Building a UI](/docs/frontend/building-a-ui.md): the components that show this data
