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

Sharing Data Across Components

Using the same query key in multiple components to share cached data without prop drilling.

Sharing Data Across Components

What you'll learn: How using the same query key in multiple components lets them all share the same cached data automatically, without passing props.

The Magic of Query Keys as Cache Identifiers

Remember how query keys act as unique identifiers for cached data? Here's where that design pays off: any component that uses the same query key gets instant access to the same cached data.

If Component A fetches user data with useQuery({ queryKey: ['user', userId] }), and Component B in a completely different part of your app uses the exact same query key, they both share the cached result. No prop drilling. No context providers. No manual coordination.

Why This Matters

Traditionally, if two distant components needed the same data, you'd either:

  • Prop drill through multiple layers (painful)
  • Use Context (adds complexity, potential re-render issues)
  • Fetch twice (wasteful, inconsistent)

TanStack Query eliminates all of this. The query key acts like a global address for that data. Any component can "dial up" that address and get the current cached value.

How It Works in Practice

Component A (navbar):

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

Component B (profile page, far away in the tree):

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

Both components instantly share the same user data. If the data is already cached, the second component doesn't even trigger a new request (thanks to request deduplication). If the cache goes stale, both components automatically update together when fresh data arrives.

Key Takeaway: Query keys create a shared cache layer that any component can tap into—eliminating prop drilling and manual state synchronization across your component tree.