Sub topic 10
A Data Access Layer and Server State
What this chapter assumes
This chapter assumes you know React hooks, TypeScript basics, and fetch with promises. It also assumes you have read the earlier chapters on feature modules and public APIs. The examples use TanStack Query v5 (@tanstack/react-query). Other server-state libraries such as SWR or RTK Query follow the same model.
Server state is not client state
Server state is data that lives on a backend and that your app holds a temporary copy of. Client state is data that exists only in the browser, such as whether a menu is open.
Server state has properties that client state lacks:
- The copy can become stale, because someone else may change the data.
- Many components may need the same data at once.
- Loading, error, and retry behavior all need handling.
- Requests can finish out of order.
Many codebases handle this with useState and useEffect in every component. That approach duplicates requests, rewrites loading flags in each file, and creates race conditions when a slow response overwrites a newer one. A data access layer fixes this by giving network code one home and giving caching to a library.
The three pieces
The layer has three parts, each in a fixed place inside a feature:
api.tsholds plain async functions that talk to the backend. They know about URLs and response shapes. They know nothing about React.hooks/holds custom hooks that wrap those functions with a server-state library. They own query keys, caching options, and invalidation.- Components call the hooks. They never call
fetchor the api functions directly.
This split gives you two benefits. You can test api functions without rendering anything. You can also change the data source (REST to GraphQL, for example) by editing one file per feature.
The api file
Each feature owns the api functions for its own data:
// src/features/orders/api.ts
export type Order = { id: string; total: number };
export async function fetchOrders(userId: string): Promise<Order[]> {
const res = await fetch(`/api/users/${encodeURIComponent(userId)}/orders`);
if (!res.ok) throw new Error(`Failed to load orders: ${res.status}`);
return res.json();
}
// 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),
});
}Two details matter here. First, fetch only rejects on network failure. A 404 or 500 resolves normally, so you must check res.ok and throw. If you skip this, the library treats the error body as successful data. Second, res.json() returns any, so the Promise<Order[]> annotation is a promise from you and not a check. For data you do not control, validate at this boundary with a schema library such as Zod.
Using the hook in a component
The provider must wrap the app once. Put it in the app/ folder:
// src/app/App.tsx
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { AppRoutes } from "./routes";
const queryClient = new QueryClient();
export function App() {
return (
<QueryClientProvider client={queryClient}>
<AppRoutes />
</QueryClientProvider>
);
}A component then reads the hook and handles each status:
// src/features/orders/components/OrderList.tsx
import { useOrders } from "../hooks/useOrders";
export function OrderList({ userId }: { userId: string }) {
const { data, isPending, isError, error } = useOrders(userId);
if (isPending) return <p>Loading...</p>;
if (isError) return <p>{error.message}</p>;
return (
<ul>
{data.map((order) => (
<li key={order.id}>
{order.id}: {order.total}
</li>
))}
</ul>
);
}If two components on the same page call useOrders("42"), the library sends one request and shares the result.
Query keys
A query key identifies a cached entry. The library compares keys by value. Treat the key like a dependency array: every variable the query function uses must appear in it. If userId is missing from the key, two users share one cache entry and one sees the other's orders.
As a feature grows, string literals scattered across hooks drift apart. A key factory keeps them in one place:
// src/features/orders/queryKeys.ts
export const orderKeys = {
all: ["orders"] as const,
list: (userId: string) => [...orderKeys.all, "list", userId] as const,
detail: (orderId: string) => [...orderKeys.all, "detail", orderId] as const,
};Keys are matched by prefix. Invalidating orderKeys.all marks every list and detail entry for orders as stale. Starting every key with the feature name also prevents collisions between features.
Writes and invalidation
A mutation changes data on the server. After it succeeds, the cached reads are out of date. The usual fix is to invalidate the affected keys so the library refetches them:
// src/features/orders/hooks/useCancelOrder.ts
import { useMutation, useQueryClient } from "@tanstack/react-query";
import { orderKeys } from "../queryKeys";
async function cancelOrder(orderId: string): Promise<void> {
const res = await fetch(`/api/orders/${encodeURIComponent(orderId)}/cancel`, {
method: "POST",
});
if (!res.ok) throw new Error(`Failed to cancel order: ${res.status}`);
}
export function useCancelOrder() {
const queryClient = useQueryClient();
return useMutation({
mutationFn: cancelOrder,
onSuccess: () => queryClient.invalidateQueries({ queryKey: orderKeys.all }),
});
}In a real feature, cancelOrder belongs in api.ts. It is inlined here to keep the example in one file.
Invalidation is simple and correct. Optimistic updates, where the UI changes before the server answers, are faster to the eye but need rollback logic. Start with invalidation and add optimism only where latency hurts.
Where each kind of state goes
| Kind of state | Example | Where it lives |
|---|---|---|
| Server state | Order list, user profile | Query cache, accessed through feature hooks |
| Local UI state | Is a dropdown open | `useState` in the component |
| Shared client state | Selected filters used by two sibling components | Lifted to the nearest common parent, or a feature-level context or store |
| URL state | Current page, search term | Router params and search params |
The rule: never copy server data into useState or a global store. The copy goes stale and the cache cannot update it. Derive values from data during render instead.
Public API and the data layer
Decide what the feature's index.ts exports. A good default is to export hooks and types and keep api.ts private:
// src/features/orders/index.ts
export { OrderList } from "./components/OrderList";
export { useOrders } from "./hooks/useOrders";
export { useCancelOrder } from "./hooks/useCancelOrder";
export type { Order } from "./api";Other features then depend on the hook's behavior (caching, error states), not on how the data is fetched.
Common errors
- Calling
fetchinside components. It bypasses the cache and spreads URLs through the UI. Move it toapi.tsand wrap it in a hook. - Missing variables in the query key. Data for one input shows up for another. Match the key to the query function's inputs.
- Not checking
res.ok. HTTP errors look like successes. - Missing
QueryClientProvider. Hooks throw an error saying noQueryClientis set. Wrap the app once. - Copying query data into state. The copy never updates. Read
datadirectly. - Forgetting invalidation after a mutation. The screen keeps showing old data until a refetch happens by chance.
- Creating
new QueryClient()inside a component body. A new client on every render discards the cache. Create it once at module level or in a stable ref.
Exercise
A product page uses useQuery({ queryKey: ["product"], queryFn: () => fetchProduct(productId) }). Users report that after moving from product 1 to product 2, they sometimes see product 1's details. What is the bug, and how do you fix it?
Show answer
The query key does not include productId, so both products share one cache entry. Add the variable to the key: queryKey: ["products", "detail", productId]. Better, put it in a key factory such as productKeys.detail(productId) so every hook builds the key the same way.
Exercise
A teammate writes const [orders, setOrders] = useState<Order[]>([]); and fills it from useOrders(userId).data in a useEffect. After useCancelOrder succeeds, the list does not change. Why, and what should they do?
Show answer
Invalidation refreshes the cached query data, but the copied state in orders is never updated from it. Remove the useState and useEffect. Read data from useOrders directly in render, and derive anything else (sorted or filtered lists) from it during render.