TanStack DB is a library that makes it really easy to build ⚡blazing fast⚡ front-ends.
Sounds amazing, right? Learn the basics with this interactive tutorial in 6-7 minutes!
We have a projects table in our database. If you click the button below, you can see all the components that to 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,
}),
);
On the project's page, the RouteComponent 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],
);
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:
Network tab in your browser's dev toolsGET request to the /api/projects endpoint, despite having 2 components using data from the projectCollectionUnless 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)
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.