Lesson 3 of 8
TanStack Query Deep Dive
Going beyond basic useQuery: dependent queries, parallel queries, infinite scrolling, prefetching, and the query key strategy that makes cache invalidation clean and predictable.
Advanced Query Patterns
import { useQuery, useQueries, useInfiniteQuery, useQueryClient } from '@tanstack/react-query';
// ---- Query key factory - centralized, type-safe ----
const queryKeys = {
users: {
all: ['users'] as const,
lists: () => [...queryKeys.users.all, 'list'] as const,
list: (filters: UserFilters) => [...queryKeys.users.lists(), filters] as const,
details: () => [...queryKeys.users.all, 'detail'] as const,
detail: (id: string) => [...queryKeys.users.details(), id] as const,
},
};
// ---- Dependent queries - run only when previous data is available ----
function UserWithPosts({ userId }: { userId: string }) {
const userQuery = useQuery({
queryKey: queryKeys.users.detail(userId),
queryFn: () => fetchUser(userId),
});
const postsQuery = useQuery({
queryKey: ['posts', 'byUser', userQuery.data?.id],
queryFn: () => fetchPostsByUser(userQuery.data!.id),
enabled: !!userQuery.data, // only run after user is loaded
});
// ...
}
// ---- Parallel queries - fetch multiple resources at once ----
function Dashboard() {
const [userQuery, statsQuery, notificationsQuery] = useQueries({
queries: [
{ queryKey: ['currentUser'], queryFn: fetchCurrentUser },
{ queryKey: ['stats'], queryFn: fetchDashboardStats },
{ queryKey: ['notifications'], queryFn: fetchNotifications, refetchInterval: 30_000 },
],
});
// All three fetch in parallel
}
// ---- Infinite queries - cursor-based pagination ----
function InfinitePostList() {
const { data, fetchNextPage, hasNextPage, isFetchingNextPage } = useInfiniteQuery({
queryKey: ['posts', 'infinite'],
queryFn: ({ pageParam }) => fetchPosts({ cursor: pageParam, limit: 20 }),
initialPageParam: undefined as string | undefined,
getNextPageParam: (lastPage) => lastPage.nextCursor, // undefined = no more pages
getPreviousPageParam: (firstPage) => firstPage.prevCursor,
});
const posts = data?.pages.flatMap(page => page.items) ?? [];
return (
<>
{posts.map(post => <PostCard key={post.id} post={post} />)}
<button
onClick={() => fetchNextPage()}
disabled={!hasNextPage || isFetchingNextPage}
>
{isFetchingNextPage ? 'Loading...' : hasNextPage ? 'Load More' : 'All loaded'}
</button>
</>
);
}
// ---- Prefetching - load data before user navigates ----
function UserListItem({ user }: { user: User }) {
const queryClient = useQueryClient();
// Prefetch user detail when hovering the list item
function handleMouseEnter() {
queryClient.prefetchQuery({
queryKey: queryKeys.users.detail(user.id),
queryFn: () => fetchUser(user.id),
staleTime: 60_000, // don't prefetch if already fresh
});
}
return (
<Link to={`/users/${user.id}`} onMouseEnter={handleMouseEnter}>
{user.name}
</Link>
);
}Tip
Tip
Practice TanStack Query Deep Dive in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.
Visual architecture and flow for TanStack Query Deep Dive
Practice Task
Note
Practice Task - (1) Write a working example of TanStack Query Deep Dive from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.
Quick Quiz
Common Mistake
Warning
A common mistake with TanStack Query Deep Dive is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready react code.
Finished this lesson?