Sub topic 3
Where Effect-Based Fetching Falls Short
Assume you know JavaScript promises, React components and JSX, useState, and basic HTTP. Fetching in an effect works for small client-only screens, but it makes each component manage loading, errors, cancellation, caching, and refetching itself.
Effect-based fetching also starts after the first render. Several components can therefore create a request waterfall: one request finishes before the component that needs it can start another request. Effects do not automatically deduplicate identical requests or retain data when a component unmounts.
Fetching with TanStack Query
TanStack Query stores server data outside a component and manages request state. A query key is an array that uniquely identifies a piece of server data.
import { useQuery } from '@tanstack/react-query';
function UserProfile({ userId }) {
const { data, error, isPending } = useQuery({
queryKey: ['user', userId],
queryFn: async ({ signal }) => {
const response = await fetch(`/api/users/${userId}`, { signal });
if (!response.ok) throw new Error(`HTTP ${response.status}`);
return response.json();
},
});
if (isPending) return <p>Loading...</p>;
if (error) return <p>Error: {error.message}</p>;
return <h1>{data.name}</h1>;
}The library can cache results, share an in-flight request, refetch stale data, and cancel work when appropriate.
Query Keys, Caching, and Stale Data
TanStack Query uses the query key as a cache address. ['user', 7] and ['user', 8] refer to different users. Include every input that changes the result in the key.
Cached data can be stale, meaning it may no longer match the server. Stale data is still useful for immediate rendering while a background refetch obtains a newer value.
Updating Server Data with Mutations
A mutation changes server data. After a successful mutation, invalidate related queries so they refetch.
const mutation = useMutation({
mutationFn: (name) => renameUser(userId, name),
onSuccess: () =>
queryClient.invalidateQueries({ queryKey: ['user', userId] }),
});Suspense and the `use` Hook
Suspense lets a component display a fallback while a child waits for data. React’s use API can read a promise during rendering in supported React environments. These features move loading coordination into rendering, but they require compatible framework and error-boundary setup.
Fetching in Server Components
A Server Component fetches on the server before sending rendered output to the browser. This can reduce client JavaScript and avoid exposing server-only access. It cannot use interactive client hooks such as useState unless a client component handles that interaction.
Choosing an Approach
| Situation | Good starting point |
|---|---|
| One small, local request | `useEffect` with cleanup |
| Shared data, caching, or refetching | TanStack Query |
| Server-rendered routes and framework data loading | Server Components or framework fetching |
Exercise
Why should userId appear in the query key when fetching a user?
Show answer
The key identifies the cached result. Including userId keeps each user's data separate and causes the query to change when the ID changes.