Skip to content
Tutorials Center
My learning

Topics

Lesson 38 of 38 ยท Projects and Practice

Practice: Cache Challenges

Practice TanStack Query with ten exercises on keys, staleTime, invalidation, optimistic updates and pagination, each with a hint and a worked solution to compare.

Reading about the cache is different from predicting what it will do. This page gives you ten challenges. Try each one before opening the solution, and use the live cache lab below to check your guesses.

The cache lab

The lab uses a real QueryClient without React, so you can call its methods directly and see the result. Press Run and read the log. Then edit the code and predict the output first.

Cache lab (no React)

Expected: the first log is 1 (the second fetch is served from cache), the entry becomes invalidated, a third fetch increases the count to 2, user 2 is read back, the two keys with swapped object properties match (true, because keys are hashed with sorted object keys) and no queries remain.

The challenges

1. The stale list

A list query has staleTime: 5 * 60 * 1000. A user adds an item with a mutation, but the list does not show it. Why, and what is the fix?

Solution

The mutation changed the server but nothing told the cache. Fresh data is never refetched, so the old list stays. Invalidate the list key in the mutation's onSuccess (or onSettled): queryClient.invalidateQueries({ queryKey: ["items"] }). Invalidation marks the data stale regardless of staleTime and refetches active queries.

2. The wrong tab

A tab component uses queryKey: ["posts"] and queryFn: () => fetchPosts(tab). All tabs show the first tab's data. Fix it.

Solution

Everything the query function reads must be in the key: queryKey: ["posts", tab]. Without it every tab shares one cache entry.

3. Zero or infinity

What is the difference between staleTime: Infinity and gcTime: Infinity?

Solution

staleTime: Infinity means the data never becomes stale, so it is not refetched automatically (manual invalidation still works). gcTime: Infinity means inactive queries are never garbage collected, so they stay in memory. They control different things: when to refetch versus when to forget.

4. The flicker

Changing a filter shows a full-page spinner each time. Keep the old results on screen instead.

Solution

Add placeholderData: keepPreviousData (import it from @tanstack/react-query) and dim the list when isPlaceholderData is true.

5. Rollback

You write the optimistic value in onMutate. Which three things must onMutate do first, and what must onError do?

Solution

Cancel outgoing refetches with cancelQueries, snapshot with getQueryData, then write with setQueryData, and return the snapshot as context. onError restores it with setQueryData(key, context.previous); onSettled invalidates.

6. Dependent queries

You need a user's projects, but only after the user loads. Write the second query.

Solution
JavaScript
const user = useQuery({ queryKey: ["user"], queryFn: fetchUser });
const projects = useQuery({
  queryKey: ["projects", user.data?.id],
  queryFn: () => fetchProjects(user.data.id),
  enabled: !!user.data?.id,
});

While enabled is false, the query stays idle (status pending, fetchStatus idle).

7. Many pages, one edit

A card lives in an infinite query. Write the setQueryData updater that renames card 7.

Solution
JavaScript
qc.setQueryData(["feed"], (old) => old && {
  ...old,
  pages: old.pages.map((p) => ({
    ...p,
    items: p.items.map((c) => (c.id === 7 ? { ...c, title: "New" } : c)),
  })),
});

8. Retry storm

A request to a protected endpoint returns 401 and the user sees "Loading" for 7 seconds. Why, and how do you avoid it?

Solution

Default retries are 3 with exponential backoff (about 1 s, 2 s, 4 s). Retrying a 401 or 404 is pointless. Use retry: (count, error) => error.status >= 500 && count < 3, or set retry: false for that query.

9. Prefetch on hover

Describe how to make a detail page feel instant when the user hovers a link.

Solution

Call queryClient.prefetchQuery({ queryKey: ["post", id], queryFn: () => fetchPost(id), staleTime: 30000 }) in onMouseEnter. The staleTime makes the later useQuery reuse the data instead of fetching again.

10. Test isolation

Two tests pass alone but the second fails when both run. What is the usual cause and cure?

Solution

They share one QueryClient, so cached data leaks between tests. Create a new client per test, with retry: false and gcTime: Infinity (or 0 for tests that check unmounting), and wrap the component with a provider that uses it.

How to practice further

Check your understanding

Quick check ยท 3 questions

of 3 answered You scored / 3 ยท perfect!

  1. 1. Which pair of keys refers to the same cache entry?

    Object properties in keys are hashed in sorted order, so their order does not matter. Array order and types do.
  2. 2. A query with staleTime: Infinity should be refreshed after a mutation. What do you call?

    invalidateQueries marks it stale and refetches it if it is being used, regardless of staleTime.
  3. 3. Which option stops a dependent query from running until a value exists?

    enabled: false keeps the query idle until the condition becomes true.

Summary

  • Everything the query function reads belongs in the key.
  • staleTime decides when to refetch; gcTime decides when to forget.
  • Invalidate after mutations; use optimistic updates with cancel, snapshot, write and rollback.
  • Use enabled, placeholderData and tuned retry to shape loading behavior.
  • Give every test its own QueryClient.

Next: back to the TanStack Query track page