Course contentsShow
← React
Lesson 1772 of 2,39642. Data Fetching LibrariesFree lesson

Query Keys with Variables

Using query keys with dynamic parameters to cache different variations of the same query.

Query Keys with Variables

What you'll learn: How to use dynamic parameters in query keys so TanStack Query can cache different variations of the same data source independently.

The Problem with Static Keys

Remember how query keys identify cached data? A key like ['user'] works great when you're always fetching the same user. But what if you need to fetch different users at different times? User #1, User #5, User #42?

If you use ['user'] for all of them, TanStack Query thinks they're all the same data — it'll serve User #1's cached data when you request User #5. Disaster!

Dynamic Keys: Arrays with Variables

The solution: include the variable parameters in your query key array.

const { data } = useQuery({
  queryKey: ['user', userId],
  queryFn: () => fetchUser(userId)
});

Now when userId changes from 1 to 5, TanStack Query sees these as different cache entries:

  • ['user', 1] → User #1's data
  • ['user', 5] → User #5's data

Think of It Like File Paths

Query keys work like folder structures:

  • ['users'] — all users
  • ['user', 5] — user 5 specifically
  • ['user', 5, 'posts'] — posts by user 5

Each unique combination gets its own cache slot.

Multiple Variables

You can include as many variables as needed:

const { data } = useQuery({
  queryKey: ['posts', { status, page, sortBy }],
  queryFn: () => fetchPosts({ status, page, sortBy })
});

When status or page changes, you get a fresh query. When they match a previous combination, you get cached results.

Key Takeaway: Include all variables that affect your data in the query key array — TanStack Query treats each unique combination as separate cached data, letting you fetch and cache multiple variations independently.