Capítulo 3 de 80

Chapter 3: Quick Start

Core Idea

The entire library boils down to three concepts used together: queries (read), mutations (write), and query invalidation (tell the cache a write changed something so reads refresh).

Key Concepts

  • Queries: useQuery({ queryKey, queryFn }) reads/subscribes to cached async data.
  • Mutations: useMutation({ mutationFn }) performs an async write and exposes a .mutate() trigger plus lifecycle callbacks (onSuccess, etc.).
  • Invalidation: queryClient.invalidateQueries({ queryKey }), typically called from a mutation's onSuccess, marks matching cached queries stale so they refetch.
  • Wiring: one QueryClient instance, provided once via QueryClientProvider at the app root; useQueryClient() retrieves it anywhere below.

Code Examples

const queryClient = new QueryClient()

function App() {
  return (
    <QueryClientProvider client={queryClient}>
      <Todos />
    </QueryClientProvider>
  )
}

function Todos() {
  const queryClient = useQueryClient()
  const query = useQuery({ queryKey: ['todos'], queryFn: getTodos })

  const mutation = useMutation({
    mutationFn: postTodo,
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['todos'] })
    },
  })

  return (
    <div>
      <ul>{query.data?.map((todo) => <li key={todo.id}>{todo.title}</li>)}</ul>
      <button onClick={() => mutation.mutate({ id: Date.now(), title: 'Do Laundry' })}>
        Add Todo
      </button>
    </div>
  )
}
  • What it demonstrates: the canonical read → write → invalidate → refetch loop that underlies almost every TanStack Query feature.

Key Takeaways

  1. Read this loop (query → mutation → invalidate) as the library's core mental model; every advanced feature (optimistic updates, infinite queries, prefetching) is a variation on it.
  2. queryClient.invalidateQueries in a mutation's onSuccess is the default, idiomatic way to keep reads in sync with writes — reach for manual cache writes only when invalidation is provably too slow.
  3. useQueryClient() is how any component below the provider reaches the shared cache without prop drilling.

Connects To

  • Queries / Mutations / Query Invalidation: full chapters on each of the three concepts introduced here.
  • Updates from Mutation Responses: the alternative to invalidation — writing the response directly into the cache.