useQuery
Reactive data fetching hook
useQuery fetches records and re-renders when data changes.
Signature
useQuery<T>(
collectionName: string,
queryFn?: (q: QueryBuilder<T>) => QueryBuilder<T>,
deps?: unknown[],
): QueryResult<T>
interface QueryResult<T> {
data: Array<Model<T> & T>
loading: boolean
error: Error | undefined
}
Basic usage
import { useQuery } from "ctrodb/react"
function TodoList() {
const { data: todos, loading } = useQuery("todos")
if (loading) return <p>Loading...</p>
return (
<ul>
{todos.map((todo) => (
<li key={todo.id}>{todo.title}</li>
))}
</ul>
)
}
With filters
function ActiveTodos() {
const { data: todos } = useQuery("todos", (q) =>
q.where("done", "==", false).sort({ createdAt: "desc" })
)
return <TodoList items={todos} />
}
With dynamic deps
function SearchResults({ query }: { query: string }) {
const { data: results } = useQuery(
"articles",
(q) => q.search("title", query),
[query],
)
return <ResultsList items={results} />
}
The deps array controls when the query function is re-evaluated.
How it works
- Runs the query on mount
- Subscribes to change events for the collection
- Re-runs the query on every change event
- Cleans up subscription on unmount
How is this guide?
Last updated on Jul 2, 2026