Skip to content

Commit 1515a23

Browse files
KyleAMathewsclaude
andauthored
Document dependency array usage for react hooks (#785)
* docs: document dependency arrays for React hooks Add comprehensive guide on using dependency arrays with useLiveQuery, useLiveInfiniteQuery, and useLiveSuspenseQuery hooks including: - When to use dependency arrays - What happens when dependencies change - Best practices with examples - Comparison to React's useEffect dependencies The API reference already documented the deps parameter, but the main guide lacked this important information for developers. * docs: add brief dependency array mention in live queries guide Add a note in the framework integration section that links to the detailed React adapter documentation for dependency arrays. This helps developers discover this important feature without cluttering the cross-framework guide with React-specific details. * docs: add link to Live Queries Guide from React adapter Add a reference to the comprehensive Live Queries Guide for developers who need full documentation on query syntax, filtering, joins, aggregations, and other query features. This keeps the React adapter docs focused on React-specific usage. --------- Co-authored-by: Claude <[email protected]>
1 parent 704a81a commit 1515a23

File tree

2 files changed

+149
-0
lines changed

2 files changed

+149
-0
lines changed

docs/framework/react/adapter.md

Lines changed: 147 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,4 +13,151 @@ npm install @tanstack/react-db
1313

1414
See the [React Functions Reference](../reference/index.md) to see the full list of hooks available in the React Adapter.
1515

16+
For comprehensive documentation on writing queries (filtering, joins, aggregations, etc.), see the [Live Queries Guide](../../guides/live-queries).
17+
1618
## Basic Usage
19+
20+
### useLiveQuery
21+
22+
The `useLiveQuery` hook creates a live query that automatically updates your component when data changes:
23+
24+
```tsx
25+
import { useLiveQuery } from '@tanstack/react-db'
26+
27+
function TodoList() {
28+
const { data, isLoading } = useLiveQuery((q) =>
29+
q.from({ todos: todosCollection })
30+
.where(({ todos }) => eq(todos.completed, false))
31+
.select(({ todos }) => ({ id: todos.id, text: todos.text }))
32+
)
33+
34+
if (isLoading) return <div>Loading...</div>
35+
36+
return (
37+
<ul>
38+
{data.map(todo => <li key={todo.id}>{todo.text}</li>)}
39+
</ul>
40+
)
41+
}
42+
```
43+
44+
### Dependency Arrays
45+
46+
All query hooks (`useLiveQuery`, `useLiveInfiniteQuery`, `useLiveSuspenseQuery`) accept an optional dependency array as their last parameter. This array works similarly to React's `useEffect` dependencies - when any value in the array changes, the query is recreated and re-executed.
47+
48+
#### When to Use Dependency Arrays
49+
50+
Use dependency arrays when your query depends on external reactive values (props, state, or other hooks):
51+
52+
```tsx
53+
function FilteredTodos({ minPriority }: { minPriority: number }) {
54+
const { data } = useLiveQuery(
55+
(q) => q.from({ todos: todosCollection })
56+
.where(({ todos }) => gt(todos.priority, minPriority)),
57+
[minPriority] // Re-run when minPriority changes
58+
)
59+
60+
return <div>{data.length} high-priority todos</div>
61+
}
62+
```
63+
64+
#### What Happens When Dependencies Change
65+
66+
When a dependency value changes:
67+
1. The previous live query collection is cleaned up
68+
2. A new query is created with the updated values
69+
3. The component re-renders with the new data
70+
4. The hook suspends (for `useLiveSuspenseQuery`) or shows loading state
71+
72+
#### Best Practices
73+
74+
**Include all external values used in the query:**
75+
76+
```tsx
77+
// Good - all external values in deps
78+
const { data } = useLiveQuery(
79+
(q) => q.from({ todos: todosCollection })
80+
.where(({ todos }) => and(
81+
eq(todos.userId, userId),
82+
eq(todos.status, status)
83+
)),
84+
[userId, status]
85+
)
86+
87+
// Bad - missing dependencies
88+
const { data } = useLiveQuery(
89+
(q) => q.from({ todos: todosCollection })
90+
.where(({ todos }) => eq(todos.userId, userId)),
91+
[] // Missing userId!
92+
)
93+
```
94+
95+
**Empty array for static queries:**
96+
97+
```tsx
98+
// No external dependencies - query never changes
99+
const { data } = useLiveQuery(
100+
(q) => q.from({ todos: todosCollection }),
101+
[]
102+
)
103+
```
104+
105+
**Omit the array for queries with no external dependencies:**
106+
107+
```tsx
108+
// Same as above - no deps needed
109+
const { data } = useLiveQuery(
110+
(q) => q.from({ todos: todosCollection })
111+
)
112+
```
113+
114+
### useLiveInfiniteQuery
115+
116+
For paginated data with live updates, use `useLiveInfiniteQuery`:
117+
118+
```tsx
119+
const { data, pages, fetchNextPage, hasNextPage } = useLiveInfiniteQuery(
120+
(q) => q
121+
.from({ posts: postsCollection })
122+
.where(({ posts }) => eq(posts.category, category))
123+
.orderBy(({ posts }) => posts.createdAt, 'desc'),
124+
{
125+
pageSize: 20,
126+
getNextPageParam: (lastPage, allPages) =>
127+
lastPage.length === 20 ? allPages.length : undefined
128+
},
129+
[category] // Re-run when category changes
130+
)
131+
```
132+
133+
**Note:** The dependency array is only available when using the query function variant, not when passing a pre-created collection.
134+
135+
### useLiveSuspenseQuery
136+
137+
For React Suspense integration, use `useLiveSuspenseQuery`:
138+
139+
```tsx
140+
function TodoList({ filter }: { filter: string }) {
141+
const { data } = useLiveSuspenseQuery(
142+
(q) => q.from({ todos: todosCollection })
143+
.where(({ todos }) => eq(todos.filter, filter)),
144+
[filter] // Re-suspends when filter changes
145+
)
146+
147+
return (
148+
<ul>
149+
{data.map(todo => <li key={todo.id}>{todo.text}</li>)}
150+
</ul>
151+
)
152+
}
153+
154+
function App() {
155+
return (
156+
<Suspense fallback={<div>Loading...</div>}>
157+
<TodoList filter="active" />
158+
</Suspense>
159+
)
160+
}
161+
```
162+
163+
When dependencies change, `useLiveSuspenseQuery` will re-suspend, showing your Suspense fallback until the new data is ready.

docs/guides/live-queries.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -161,6 +161,8 @@ export class UserListComponent {
161161
}
162162
```
163163

164+
> **Note:** React hooks (`useLiveQuery`, `useLiveInfiniteQuery`, `useLiveSuspenseQuery`) accept an optional dependency array parameter to re-execute queries when values change, similar to React's `useEffect`. See the [React Adapter documentation](../../framework/react/adapter#dependency-arrays) for details on when and how to use dependency arrays.
165+
164166
For more details on framework integration, see the [React](../../framework/react/adapter), [Vue](../../framework/vue/adapter), and [Angular](../../framework/angular/adapter) adapter documentation.
165167

166168
### Using with React Suspense

0 commit comments

Comments
 (0)