Sub topic 3
Dependent and Conditional Queries
Prerequisites: you should know React hooks, TypeScript, async/await, and basic TanStack Query usage.
Dependent and conditional queries
A dependent query needs data from another query. Use enabled to prevent it from running too early:
const { data: user } = useQuery({
queryKey: ['user', email],
queryFn: () => fetchUser(email),
})
const projects = useQuery({
queryKey: ['projects', user?.id],
queryFn: () => fetchProjects(user!.id),
enabled: user !== undefined,
})The project request waits until the user request succeeds. A conditional query can use the same option, such as enabled: isOpen, to fetch only when a dialog is visible.
Optimistic updates with rollback
An optimistic update changes the cache before the server responds. In onMutate, cancel related queries, save the old value, and write the expected value. In onError, restore the saved value. In onSettled, invalidate the query so the server remains authoritative.
Paginated lists and keeping previous data
Put the page number in the query key:
useQuery({
queryKey: ['projects', page],
queryFn: () => fetchProjects(page),
placeholderData: keepPreviousData,
})placeholderData keeps the old page visible while the new page loads. Disable navigation when there is no next page or a request is pending.
Infinite scrolling
useInfiniteQuery stores several response pages in one cache entry. getNextPageParam returns the next cursor, or undefined when the list ends.
const result = useInfiniteQuery({
queryKey: ['projects'],
queryFn: ({ pageParam }) => fetchProjects(pageParam),
initialPageParam: 0,
getNextPageParam: (page) => page.nextCursor ?? undefined,
})Render result.data?.pages.flatMap((page) => page.items) and call fetchNextPage() from a “Load more” button or an intersection observer.
Prefetching
Prefetch data when a user is likely to need it, such as on link hover:
queryClient.prefetchQuery({
queryKey: ['project', id],
queryFn: () => fetchProject(id),
})The destination component can then read the warm cache immediately.
Devtools, testing, and hydration
React Query Devtools show query keys, cached data, stale status, and active requests. They make incorrect keys and unexpected refetches easier to find.
For tests, create a fresh QueryClient per test, set retry: false, provide it with QueryClientProvider, and mock the network response. Test pending, error, success, and mutation states separately.
For server rendering, the server prefetches queries, calls dehydrate, and sends the dehydrated state to the browser. The client calls hydrate before rendering. This avoids a duplicate initial request and lets the server-rendered HTML contain real data.
Exercise
Why should a dependent query include the dependency in its query key?
Show answer
The key identifies the cached result, so each dependency value receives separate data instead of sharing an incorrect cache entry.