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

Query Function Context and Signals

Using the queryKey and signal from query function context for dynamic fetching and cancellation.

Query Function Context and Signals

You'll learn how to access query metadata and cancellation signals inside your query functions for smarter, more dynamic data fetching.

The Query Function Context Object

Every query function receives a special context object as its first parameter. This object contains useful metadata about the query itself, including:

  • queryKey: The exact key used for this query
  • signal: An AbortSignal for request cancellation
  • meta: Custom metadata you can attach to queries

Think of it like a function receiving "mission briefing" — not just what to fetch, but how it's being called and when to abort.

Accessing queryKey for Dynamic Fetching

const fetchUser = async ({ queryKey }) => {
  const [_key, userId] = queryKey; // Extract variables from key
  const response = await fetch(`/api/users/${userId}`);
  return response.json();
};

// In your component
useQuery({
  queryKey: ['user', userId],
  queryFn: fetchUser // Automatically receives context
});

This lets your query function read its own variables directly from the key!

Using signal for Cancellation

The signal enables automatic cleanup when queries are cancelled (component unmounts, key changes, etc.):

const fetchPosts = async ({ queryKey, signal }) => {
  const [_key, category] = queryKey;
  const response = await fetch(`/api/posts?category=${category}`, { signal });
  return response.json();
};

When TanStack Query cancels the request, fetch stops mid-flight — saving bandwidth and preventing race conditions.

Why This Matters

Without context, you'd need to wrap every query in a custom function just to pass parameters. With it, your query functions become self-contained and reusable.

Key Takeaway: The query function context gives you queryKey for dynamic parameters and signal for automatic request cancellation, making your data fetching cleaner and safer.