Skip to content
Tutorials Center
My learning

Topics

Lesson 10 of 38 ยท Queries and Keys

select, queryOptions and Reusable Queries

Transform cached data with select, share one definition across hooks and the client with queryOptions, and learn how structural sharing limits re-renders.

Once a few components use the same data, three questions appear. How do I read just a piece of it without a second request? Where do I define the key and function so they stay together? And how do I stop components from re-rendering when nothing they show has changed? The answers are select, queryOptions and structural sharing, and they are the finishing touches of this chapter.

select: derive a view of cached data

select is a function that receives the cached data and returns what the component actually wants. The cache keeps the full response. The hook returns the selected value.

JSX
const { data: openCount } = useQuery({
  queryKey: ["todos"],
  queryFn: fetchTodos,
  select: (todos) => todos.filter((t) => !t.done).length,
});

Two components can subscribe to the same key with different select functions, and still cause only one request. One component renders the list, another the count, a third the titles only.

Two views of one cache entry

Three different shapes, one request. Note that select does not change what is stored; calling queryClient.getQueryData(["todos"]) would still return the full array.

select and re-renders

A component with select re-renders only when the selected result changes (compared structurally). If a background refetch brings new data but the open count is still 2, the OpenCount component does not re-render. This makes select a performance tool as well as a convenience.

Keep select pure and cheap. It runs when the data or the function changes. An inline arrow function is a new function on every render, which means it re-runs on every render. For heavy transformations, define the function outside the component, or wrap it in useCallback, so it runs only when the data actually changes.

Structural sharing

When a refetch returns data, Query compares it with the previous result and reuses old object references for every part that is deeply equal. Only the parts that really changed get new references.

JavaScript
// before refetch                      // after refetch (only todo 2 changed)
[{ id: 1, ... }, { id: 2, ... }]       [{ id: 1, ... }, { id: 2, done: true }]
// todos[0] keeps the SAME reference, todos[1] is new

This is why React.memo components and useEffect dependencies on data or on nested objects do not fire for unchanged data. It works on JSON-like data. If your function returns class instances or very large payloads and the comparison costs more than it saves, you can disable it with structuralSharing: false.

queryOptions: define a query once

When a query is used in several places, it is easy to let the key and function drift apart. queryOptions is a helper that returns the options object unchanged at runtime but gives you type safety and a single definition:

JavaScript
import { queryOptions } from "@tanstack/react-query";

export function todoQueryOptions(id) {
  return queryOptions({
    queryKey: ["todos", "detail", id],
    queryFn: () => fetchTodo(id),
    staleTime: 30_000,
  });
}

Now the same object works with hooks and with imperative client methods:

JSX
useQuery(todoQueryOptions(5));
useSuspenseQuery(todoQueryOptions(5));
queryClient.prefetchQuery(todoQueryOptions(5));
queryClient.ensureQueryData(todoQueryOptions(5));
queryClient.getQueryData(todoQueryOptions(5).queryKey);

In TypeScript the data type flows from the queryFn into getQueryData, so you do not repeat generics. In JavaScript it is still the best way to ensure a loader and a component use exactly the same key and function. This ties in with the key factories from Query Keys: the factory builds the key, and the options helper bundles it with the function and the settings.

One definition, hook and imperative use

prefetchQuery accepts the same object a hook does. After it finishes, getQueryData finds the product under the key the options helper defined. Prefetching gets a full treatment in Prefetching and Initial Data.

A tidy file layout

A common structure is one module per resource that exports the options builders and nothing else, so the key, function and defaults live in exactly one place:

TEXT
src/
  queries/
    todos.js      // todosQueryOptions, todoQueryOptions(id)
    users.js      // userQueryOptions(id)

Components import these and add only what is specific to them (select, enabled, a different staleTime). That keeps the data layer thin, testable and boring, which is what you want.

Common mistakes

  • Doing the transform in the queryFn. If queryFn filters the data, the cache stores the filtered version and other components cannot see the full list. Keep the cache raw and use select.
  • Expensive inline select. It reruns every render. Move it out or memoize it.
  • Mutating inside select. select must not change the cached objects. Return new values.
  • Different options for one key. Two hooks with the same key but different queryFn produce confusing results, because only one function runs per key. queryOptions prevents that.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does select change?

    The cache keeps the full response. select only derives the value that this observer receives.
  2. 2. Two components use the same key with different select functions. How many requests are sent?

    They share one cache entry, so one request serves both.
  3. 3. What does queryOptions do at runtime?

    queryOptions is an identity helper that lets one definition be used by hooks and client methods with full type inference.
  4. 4. What is structural sharing?

    It keeps references of unchanged data stable, so memoized components and effects do not re-run needlessly.

Summary

  • select derives a view of cached data; the cache itself stays raw and complete.
  • Components with select re-render only when their selected result changes.
  • Structural sharing keeps references of unchanged data stable across refetches.
  • queryOptions defines key, function and defaults once, for hooks and for client methods.
  • Keep transformations out of the queryFn; do them with select.

Next: Mutations with useMutation