import {Link} from '@tanstack/react-router' import {GHLink, HighLightComponent, OpenAPIRequestsPanelLink} from "/src/components/tutorial"
What are collections?#
A quick demo#
Let's start with a quick demo and it'll all make sense. We have a projects table in our database. If you click the button below, you can see all the components that display data from this table:
In a traditional React app, both of them would probably fetch the data they need from the server, managing their own cache. If you update something somewhere (e.g. rename a project), you need to manually update the cache, and after a while even knowing what to update becomes a challenge.
TanStack DB provides you with a new option. You can store the projects' data in a collection, and use it as a single source of truth everywhere.
In the AppSidebar component, we use this query to get the list of projects:
const { data: projects } = useLiveQuery((q) =>
q.from({
project: projectsCollection,
}),
);
Highlight `AppSidebar`
On the project's page, the EditableProjectDetails component loads only the data relevant for the currently viewed project:
const {
data: [project],
} = useLiveQuery(
(q) => q
.from({ project: projectsCollection })
.where(({ project }) => eq(project.id, projectId)),
// This hook has a dependency array as seen below.
// Every time the `projectId` changes (i.e. we navigate
// to a new page), the query is executed again
[projectId],
);
Highlight `RouteComponent`
"So many queries... Isn't that ...slow?"#
Thankfully, no, and there are two reasons why.
Multiple queries using the same collection will sync the collection with the backend only once, and use the cache the rest of the times.
To check it, follow these steps:
- open the "API Requests" panel by clicking here
- reload the page (click here)
- see that there is only one
GETrequest to the/api/projectsendpoint, despite having 2 components using data from theprojectsCollection - If you navigate to any other project page, you shouldn't see more requests made
Unless the cache needs to be revalidated (because the state has been mutated or went stale).
Live queries are updated incrementally (they use
d2ts, a differential dataflow library)- this results in sub-millisecond execution times (even for complex queries)
- which means that it's BLAZING FAST!!! ⚡⚡⚡
Querying multiple collections#
Yes, you can even use innerJoin() and other join operations to query multiple collections. This demo doesn't have an example for that yet, but you can check the documentation if you're interested.