Data Fetching and Client Caching

Topics Covered

The Fetching Layer

Why a dedicated layer

The layers from component to network

Query keys are the contract

Loading and error states

Avoiding request waterfalls

What the interviewer is checking

Almost every frontend prompt involves data that lives on a server: a feed, a set of search results, a chat history, a product page, an inbox. The previous lesson on state management said that server state is a cached copy of data someone else owns, and that it belongs in a dedicated layer rather than in a client store. This lesson designs that layer. It covers how requests flow through the client, how a cache stores and shares responses, how stale data is refreshed, how mutations update the cache, how pagination and prefetching work on the client and how the browser's own caches fit in.

In the framework from the first lesson, this material lives mostly in step three, data model and state, and step four, the interface with the server. It is also a favourite deep dive, because it is where perceived speed is won or lost.

Why a dedicated layer

The naive approach is to fetch inside each component: on mount, call fetch, store the result in local state, show a spinner while waiting and an error if it fails. That works for one component. It breaks down quickly across an app. Two components that need the same data fire two identical requests. Navigating away and back throws the data away and shows a spinner again. Nothing refreshes when the data changes on the server. A mutation in one screen leaves another screen showing old values. Every component reimplements loading, error, retry and cancellation slightly differently, and each one has its own bugs.

A dedicated data layer fixes these problems in one place. Components declare what data they need, identified by a key, and the layer decides whether to fetch, whether to reuse a cached copy, when to refresh and how to share results. Libraries such as TanStack Query, SWR, Apollo Client, Relay, RTK Query and the data loaders built into frameworks such as React Router (which absorbed Remix) and Next.js implement this idea with different trade-offs. You do not have to name one in the interview, but you should describe the layer they provide.

The layers from component to network

Picture four layers. At the top, components call a hook or a loader with a key, such as the post with id 42 or the first page of the home feed. Beneath that sits the query cache, a map from keys to entries, where each entry holds the data, its status, when it was last fetched and how many components are currently using it. Beneath the cache is the API client, a thin module that builds requests, attaches authentication headers, parses responses, maps errors into a consistent shape and applies retry and timeout rules. At the bottom is the network itself.

Components ask the cache for data by key; only the API client talks to the network.

The key design rule is that only the API client talks to the network, and only the cache talks to the API client. Components never call fetch directly. That rule gives you one place to add authentication refresh, one place to log failures, one place to handle a session expiry response and one place to change the base URL or add a request header. It also makes testing easy: replace the API client with a fake and every screen runs offline.

typescript
1// api client: the only module that knows about HTTP
2export const api = {
3  getPost: (id: string) => request<Post>(`/posts/${id}`),
4  getFeed: (cursor?: string) => request<FeedPage>(`/feed?cursor=${cursor ?? ""}`),
5};
6// component: asks the cache by key, never fetches directly
7const { data, status } = useQuery({ queryKey: ["post", id], queryFn: () => api.getPost(id) });

Query keys are the contract

The key is the most important design decision in the layer. It identifies a piece of server data uniquely and includes every parameter that changes the response. The post with id 42 has the key post and 42. Page two of a search for shoes sorted by price has the key search, shoes, price and the cursor for page two. If two requests would return the same data, they should have the same key. If they would return different data, the keys must differ.

Good keys give you three things almost for free. Deduplication: if three components ask for the same key while a request is in flight, the cache sends one request and shares the result. Sharing: a component that mounts later reads the cached entry instead of fetching again. Targeted invalidation: after a mutation you can mark every key that starts with post and 42 as stale without touching anything else.

A shared cache key turns three simultaneous requests into one.

A common mistake is a key that leaves out a parameter. If the search key omits the sort order, changing the sort returns the cached results for the old order, and the user sees the wrong list. Another is a key that includes something irrelevant, such as a freshly created object or a timestamp, which turns every render into a new key and defeats caching entirely.

Loading and error states

A data layer also standardises status. Each entry is pending, success or error, and separately it may be fetching in the background. That distinction matters. Pending with no data means show a skeleton. Success while refetching means keep showing the data and perhaps a subtle indicator. Error with old data means keep the old data on screen and show a small error notice, rather than replacing a full screen of useful content with an error page because a background refresh failed.

Design loading states per region, not per page. A product page has a header, a gallery, a price block, reviews and recommendations. Each region can load independently, show its own skeleton and fail on its own. If recommendations fail, the rest of the page should still work. Skeletons should match the final layout closely so the page does not jump when content arrives, which the performance lesson connects to layout shift.

Avoiding request waterfalls

A waterfall happens when one request cannot start until another finishes. A page fetches the user, then uses the user's team id to fetch the team, then uses the team's project ids to fetch projects. Three round trips of two hundred milliseconds each make the page wait six hundred milliseconds before it can show projects, even if each request is fast on the server.

Component based fetching creates waterfalls by accident. A parent fetches, renders a child only when its data arrives, and the child then starts its own fetch. The fixes are to hoist data requirements to the route level so all independent requests start in parallel as soon as navigation begins, to ask the API for a combined response when requests are truly dependent, or to let the server render the first screen with the data already included, as the rendering strategies lesson discussed. GraphQL clients such as Relay go further and compose each component's data requirements into one query per screen.

In the interview, it is worth saying explicitly that route level loaders start the requests for a screen in parallel during navigation, before any component renders. That single sentence shows you know where waterfalls come from.

What the interviewer is checking

The interviewer wants to see a layered design with one place for network concerns, a clear idea of cache keys, deduplication and sharing, sensible loading and error states per region, and awareness of waterfalls. A strong candidate describes the query key for each main screen, explains what happens when two components need the same data and says how the first screen avoids sequential requests. A weak candidate says we fetch in a use effect and store it in state, which is exactly the pattern the layer exists to replace.

Name the keys for each screen

When you describe the data layer, list the query keys for the main screens, such as feed with a cursor, post by id and user by id. Keys make deduplication, sharing and invalidation concrete, and they give the interviewer something specific to probe.