Sub topic 10
A data access layer and server state
This chapter assumes you can write React components and hooks, know basic TypeScript, and have used fetch. It also assumes you have read the earlier chapters on feature modules and where state lives.
Server state is not UI state
Server state is data that lives on a server and that your app only borrows, such as a list of orders. It can change without your app knowing, it can be shared by many components, and it can go stale. UI state, such as whether a dropdown is open, belongs only to the browser.
Treating server state like UI state is a common source of bugs. You end up writing useState and useEffect in every component to load data, track loading, and handle errors. The same request then gets repeated in several places.
The layers
Split data access into three layers, each with one job:
api.tsholds plain functions that talk to the network.- A custom hook wraps those functions with a server-state library.
- Components call the hook and render the result.
The api file
Each feature keeps its network code in its own api.ts. These functions know URLs and response shapes, and nothing about React.
// 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();
}The res.ok check matters. fetch only rejects on network failure, so a 404 or 500 looks like success unless you throw yourself.
The hook
The hook connects the api function to a server-state library. This example uses TanStack Query.
// 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),
});
}A component now needs one line:
const { data, isPending, error } = useOrders(userId);The library handles caching, de-duplicating identical requests, retries, and refetching when the window regains focus. You no longer write that code yourself.
Keep the boundary clean
Export useOrders from the feature's index.ts, and keep fetchOrders private. Other features then depend on the hook, not on your URLs. If the endpoint changes, only api.ts changes.
Common errors
- Calling
fetchinside a component. This spreads URLs through the UI and makes the code hard to test. - Copying query data into
useState. The copy goes stale when the cache refreshes. Readdatadirectly, or derive values from it during render. - Putting server data in a global store. A store like Redux then needs its own loading, error, and invalidation logic. Let the server-state library own that data.
- Skipping the
res.okcheck. Errors then arrive as malformed data instead of as errors.
Exercise
A teammate's component calls fetch("/api/orders") in a useEffect, stores the result in useState, and a second component does the same. Name two problems and say how the three-layer structure fixes them.
Show answer
The same request runs twice, and each component must handle loading, errors, and staleness on its own. Move the call to fetchOrders in the feature's api.ts, wrap it in a useOrders hook that uses useQuery, and have both components call the hook. The library then shares one cached request and manages loading and error state, and the URL lives in one place.