liveBook · Manning

Query key

As explained in React Hooks in Action: With Suspense and Concurrent Mode

A query key is a structured identifier that uniquely describes a React Query data query for caching and lookup.

A query key is a structured identifier that describes a React Query data query. React Query uses it to locate cached data, return existing results immediately, and associate background refetches with the same query. section 10.3.3

Choose the key structure to match the data being requested:

  • Use a simple string such as "bookables" when components request the same collection. section 10.3.3
  • Use a serializable array such as ["bookings", bookableId, start, end] when parameters distinguish the requested data. section 10.3.3
  • Reuse an associated key with the query client to retrieve cached data or supply initial data to another query. section 10.3.4

Bookable-specific bookings

A bookings hook identifies its result by bookable, start date, and end date: ["bookings", bookableId, start, end]. React Query can therefore distinguish booking results for different selections and date ranges. section 10.3.3

Listing 10.12 useBookings calling useQuery
import {useQuery} from "react-query";
 
export function useBookings (bookableId, startDate, endDate) {
  const start = shortISO(startDate);
  const end = shortISO(endDate);
 
  const urlRoot = "http://localhost:3001/bookings";
 
  const queryString = `bookableId=${bookableId}` +
    `&date_gte=${start}&date_lte=${end}`;
 
  const query = useQuery(                           #1
    ["bookings", bookableId, start, end],           #2
    () => getData(`${urlRoot}?${queryString}`)      #3
  );
 
  return {
    bookings: query.data ? transformBookings(query.data) : {},
    ...query
  };
}
#1 Call the useQuery hook.
#2 Specify an array as the query key.
#3 Provide an asynchronous data-fetching function.

Inspect the complete useBookings example, including the structured query key and asynchronous fetch function. section 10.3.3

How React Hooks in Action: With Suspense and Concurrent Mode covers it

How deep it goes
Defines string, array, and serializable object keys, then applies them to cache access without detailing cache staleness rules.
Examples
Uses shared bookables data, parameterized bookings, and cached bookable details in an edit form.
What it assumes
Assumes familiarity with React hooks and asynchronous fetching while introducing React Query's cache and useQuery workflow.
What you can do after
Builds React Query calls with shared or parameterized keys and retrieves matching data from the query cache.
How it connects
Links query keys to useQuery, caching, query clients, initial data, and server-state mutations.

Also explained in

Compare how 2 books explain query key →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of React Hooks in Action: With Suspense and Concurrent Mode. The section links point to the parts of the book it draws on.