liveBook · Manning

useQuery

As explained in React in Depth

useQuery is a TanStack Query hook that declares and retrieves asynchronously fetched data for a component.

useQuery declares an asynchronous server-data request for a component. It combines an existing query function with a queryKey that identifies the cached result, then exposes data and loading state for rendering. section 9.3.2

Choose query keys that describe every parameter affecting the request:

  • Use ["customers"] for an unparameterized customer list. section 9.3.2
  • Include identifiers, pages, or search values in the key, such as ["customer", { id: 1 }] or ["customers", { page: 3 }]. section 9.3.2
  • Handle the initially undefined data state before mapping or rendering results. section 9.3.2
function Customers() {
  const { data, isLoading } = useQuery({     #1
    queryKey: ["customers"],  #1
    queryFn: getCustomers,    #1
  );    #1
  if (isLoading) return "Loading...";     #2
  return (
    <>
      {data.map((customer) => (    #3
          <Customer key={customer.id} {...customer} />
      ))}
    </>
  );
}

A minimal component query shows the request, loading branch, and rendering path. section 9.3.2

How React in Depth covers it

How deep it goes
Explains query functions, cache-oriented keys, loading state, and asynchronous data without covering hook internals.
Examples
Uses customer lists, individual customers, paginated results, name searches, and a loading branch.
What it assumes
Assumes an existing server-facing query function and teaches query-key construction and asynchronous result handling.
What you can do after
Apply it via TanStack Query to fetch, identify, and render asynchronous data in a component.
How it connects
Connects query keys and cache invalidation with useMutation and server data.

Also explained in

Compare how 2 books explain useQuery →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of React in Depth. The section links point to the parts of the book it draws on.