Skip to content
Source
Sign inSign up
TanStack/query
Open History to see the last commit

reactive-controllers-vs-hooks.md

111 lines5.3 KB

1---
2id: reactive-controllers-vs-hooks
3title: Reactive Controllers vs Hooks
4---
5​
6React Query examples use hooks. Lit Query uses reactive controllers.
7​
8The job is similar: subscribe a component to a `QueryClient`, read the latest result, and update the component when the cache changes. The integration point is different because Lit components use the `ReactiveControllerHost` interface instead of React's render and hook system.
9​
10## Mapping the Concepts
11​
12| React Query | Lit Query |
13| --------------------------- | ---------------------------------------------- |
14| `useQuery(options)` | `createQueryController(this, options)` |
15| `useQueries(options)` | `createQueriesController(this, options)` |
16| `useMutation(options)` | `createMutationController(this, options)` |
17| `useInfiniteQuery(options)` | `createInfiniteQueryController(this, options)` |
18| `useIsFetching(options)` | `useIsFetching(this, options)` |
19| `useIsMutating(options)` | `useIsMutating(this, options)` |
20| `useMutationState(options)` | `useMutationState(this, options)` |
21| Hook result object | Callable result accessor |
22| React context provider | `QueryClientProvider` custom element |
23| Component render rerun | `host.requestUpdate()` |
24​
25## Host-Bound APIs
26​
27Lit APIs that subscribe a component to query or mutation state receive a `host` as the first argument:
28​
29```ts
30class TodosView extends LitElement {
31 private readonly todos = createQueryController(this, {
32 queryKey: ['todos'],
33 queryFn: fetchTodos,
34 })
36```
37​
38`this` is valid because `LitElement` implements `ReactiveControllerHost`. The controller attaches to the host, subscribes when the host connects, requests updates when the query result changes, and unsubscribes when the host disconnects.
39​
40The host-bound APIs are [`createQueryController`](../reference/functions/createQueryController.md), [`createQueriesController`](../reference/functions/createQueriesController.md), [`createInfiniteQueryController`](../reference/functions/createInfiniteQueryController.md), [`createMutationController`](../reference/functions/createMutationController.md), [`useIsFetching`](../reference/functions/useIsFetching.md), [`useIsMutating`](../reference/functions/useIsMutating.md), and [`useMutationState`](../reference/functions/useMutationState.md).
41​
42[`useQueryClient`](../reference/functions/useQueryClient.md) is different. It is not a reactive controller, does not accept a host, does not subscribe, and throws synchronously if no single default client is available. Use it only for imperative code that runs while exactly one `QueryClientProvider` is connected. Inside host-bound APIs, prefer the provider context or pass an explicit `QueryClient`.
43​
44## Reading Results
45​
46Lit Query controller creators return a callable accessor with a `current` property:
47​
48```ts
49const query = this.todos()
50const sameQuery = this.todos.current
51```
52​
53Render methods normally call the accessor:
54​
55```ts
56render() {
57 const query = this.todos()
58​
59 if (query.isPending) return html`Loading...`
60 if (query.isError) return html`Error: ${query.error.message}`
61​
62 return html`<todo-list .items=${query.data}></todo-list>`
64```
65​
66## Reactive Options
67​
68If query options depend on host state, pass a function. Lit Query re-reads function accessors during host updates:
69​
70```ts
71class ProjectView extends LitElement {
72 static properties = {
73 projectId: { type: Number },
74 }
75​
76 projectId = 1
77​
78 private readonly project = createQueryController(this, () => ({
79 queryKey: ['project', this.projectId],
80 queryFn: () => fetchProject(this.projectId),
81 }))
83```
84​
85If options are static, pass an object. If you mutate a static options object yourself, call the controller helper that causes the observer to see the new options, such as `refetch`, or prefer a function accessor for reactive state.
86​
87## Provider Context
88​
89Host-bound APIs can receive an explicit `QueryClient`, but most apps render under [`QueryClientProvider`](../reference/classes/QueryClientProvider.md). The provider uses Lit context to deliver the client to descendant controllers.
90​
91```ts
92customElements.define('query-client-provider', QueryClientProvider)
93```
94​
95```ts
96html`
97 <query-client-provider .client=${queryClient}>
98 <todos-view></todos-view>
99 </query-client-provider>
101```
102​
103Custom element registration is always the application's responsibility.
104​
105`QueryClientProvider` also registers its client in a process-local fallback store for [`useQueryClient`](../reference/functions/useQueryClient.md) and [`resolveQueryClient`](../reference/functions/resolveQueryClient.md). That fallback is intentionally conservative:
106​
107- If no provider is connected, `useQueryClient()` throws.
108- If exactly one distinct client is connected, `useQueryClient()` returns it.
109- If multiple distinct clients are connected in the same JavaScript context, `useQueryClient()` and `resolveQueryClient()` throw because the fallback would be ambiguous.
110​
111Multiple roots, micro-frontends, test suites with shared modules, and nested apps should avoid relying on the process-local fallback. Render host-bound controllers under the right provider, pass an explicit `QueryClient` to the controller, or cleanly disconnect providers between tests.