Open History to see the last commit
1---
2title: TanStack DB Preact Adapter
3id: adapter
4---
5
6## Installation
7
8```sh
9npm install @tanstack/preact-db
10```
11
12`@tanstack/preact-db` supports Preact 10 and later and ships as ES modules.
13
14Queries read concrete source Collections. Preact has no `DbProvider` yet, so it does not bind collection descriptors or read from a `DbClient`; a query over a descriptor throws when it is consumed. Use `@tanstack/react-db` or `@tanstack/svelte-db` for `DbClient`-based SSR and hydration.
15
16## Preact Hooks
17
18See the [Preact Functions Reference](./reference/index.md) to see the full list of hooks available in the Preact Adapter.
19
20For comprehensive documentation on writing queries (filtering, joins, aggregations, etc.), see the [Live Queries Guide](../../guides/live-queries).
21
22## Basic Usage
23
24### useLiveQuery
25
26The `useLiveQuery` hook creates a live query that automatically updates your component when data changes:
27
28```tsx
29import { eq, useLiveQuery } from '@tanstack/preact-db'
30
31function TodoList() {
32 const { data, isLoading } = useLiveQuery((q) =>
33 q
34 .from({ todos: todoCollection })
35 .where(({ todos }) => eq(todos.completed, false))
36 .select(({ todos }) => ({ id: todos.id, text: todos.text })),
37 )
38
39 if (isLoading) return <div>Loading...</div>
40
41 return (
42 <ul>
43 {data.map((todo) => (
44 <li key={todo.id}>{todo.text}</li>
45 ))}
46 </ul>
47 )
48}
49```
50
51`useLiveQuery` accepts a query callback, a `{ query }` config object, or an existing live-query Collection. Return `undefined` or `null` from the callback to disable the query; a disabled query reports `status: 'disabled'` and has no `data` or `state`:
52
53```tsx
54function UserTodos({ userId }: { userId?: string }) {
55 const { data, isEnabled } = useLiveQuery((q) =>
56 userId
57 ? q
58 .from({ todos: todoCollection })
59 .where(({ todos }) => eq(todos.userId, userId))
60 : undefined,
61 )
62
63 if (!isEnabled) return <div>Select a user</div>
64 return <div>{data?.length} todos</div>
65}
66```
67
68### Query Identity
69
70Preact live query hooks derive the live query identity from structured query IR. The hook runs the query builder on each render, normalizes the resulting IR, and uses that as the identity. When the derived identity changes, the old live query collection is cleaned up and a new one is created.
71
72That means normal structured queries need no `queryKey` and no dependency array. Captured values inside structured expressions become part of the derived identity:
73
74```tsx
75function FilteredTodos({ minPriority }: { minPriority: number }) {
76 const { data } = useLiveQuery((q) =>
77 q
78 .from({ todos: todoCollection })
79 .where(({ todos }) => gt(todos.priority, minPriority)),
80 )
81
82 return <div>{data.length} high-priority todos</div>
83}
84```
85
86While a hook is mounted, each source Collection ID its queries read must keep referring to the same Collection object. If a render supplies a different source object with a previously used ID, the hook throws `SourceCollectionIdReuseError` instead of returning rows from the old source. To reuse an ID, unmount the hook, clean up its source, then mount the replacement. Separate hooks can use the same ID.
87
88#### When to Use Query Keys
89
90Use `queryKey` when DB cannot derive identity from structured IR. The common case is a functional query variant such as `.fn.where`, `.fn.select`, or `.fn.having`. Without a `queryKey`, such a query throws `UnhashableQueryIRError`:
91
92```tsx
93function SearchTodos({ search }: { search: string }) {
94 const { data } = useLiveQuery({
95 queryKey: [todoCollection.id, 'search', search],
96 query: (q) =>
97 q
98 .from({ todos: todoCollection })
99 .fn.where(({ todos }) =>
100 todos.text.toLowerCase().includes(search.toLowerCase()),
101 ),
102 })
103
104 return <div>{data.length} matching todos</div>
105}
106```
107
108An explicit `queryKey` is the caller's identity contract. Represent every value the opaque logic captures in the key, and change the key when its source object changes, even if the source ID stays the same. Use a primitive scope token in the key; Collection objects cannot be hashed there.
109
110#### What Happens When Identity Changes
111
112When the derived identity or explicit query key changes:
113
1141. The previous live query collection is cleaned up
1152. A new query is created with the updated values
1163. The component re-renders with the new data
117
118### useLiveInfiniteQuery
119
120For paginated data with live updates, use `useLiveInfiniteQuery`:
121
122```tsx
123const { data, pages, fetchNextPage, hasNextPage } = useLiveInfiniteQuery(
124 (q) =>
125 q
126 .from({ posts: postsCollection })
127 .where(({ posts }) => eq(posts.category, category))
128 .orderBy(({ posts }) => posts.createdAt, 'desc'),
129 {
130 pageSize: 20,
131 },
132)
133```
134
135The query must include `.orderBy()`. The hook keeps one live query collection and widens its window as pages load, so every loaded page stays live. Its identity follows `useLiveQuery`: pass `queryKey` in the config for a functional query variant.
136
137`fetchNextPage()` returns a promise that resolves after the page request settles. A failed page load does not reject the promise or change `status`; it appears as a request error in the returned `health` tree.
138
139This hook widens an ordered live query; it is not TanStack Query's `useInfiniteQuery`. `getNextPageParam` is rejected. `initialPageParam` only labels the returned pages; it does not set a server cursor or skip remote rows. For server pagination, use an on-demand Query Collection whose `queryFn` fulfills `meta.loadSubsetOptions`. See the [server pagination guide](../../collections/query-collection.md#server-pagination-with-live-queries).
140
141### Using Pre-created Collections
142
143Pass an existing live query collection to share one query across components. The hook starts its sync and leaves its retention policy to the caller:
144
145```tsx
146const activeTodos = createLiveQueryCollection((q) =>
147 q.from({ todos: todoCollection }).where(({ todos }) => eq(todos.active, true)),
148)
149
150function ActiveTodos() {
151 const { data, collection } = useLiveQuery(activeTodos)
152 return <div>{data.length} active todos</div>
153}
154```