Skip to content
Source
Sign inSign up
TanStack/db
Open History to see the last commit

overview.md

698 lines25.8 KB

1---
2title: Overview
3id: overview
4---
5​
6# TanStack DB - Documentation
7​
8Welcome to the TanStack DB documentation.
9​
10TanStack DB is a reactive client store for building super fast apps on sync. It extends TanStack Query with collections, live queries and optimistic mutations.
11​
12## Contents
13​
14- [How it works](#how-it-works) — understand the TanStack DB development model and how the pieces fit together
15- [API reference](#api-reference) — for the primitives and function interfaces
16- [Usage examples](#usage-examples) — examples of common usage patterns
17- [More info](#more-info) — where to find support and more information
18​
19## How it works
20​
21TanStack DB works by:
22​
23- [defining collections](#defining-collections) typed sets of objects that can be populated with data
24- [using live queries](#using-live-queries) to query data from/across collections
25- [making optimistic mutations](#making-optimistic-mutations) using transactional mutators
26​
27```tsx
28// Define collections to load data into
29const todoCollection = createCollection({
30 // ...your config
31 onUpdate: updateMutationFn,
32})
33​
34const Todos = () => {
35 // Bind data using live queries
36 const { data: todos } = useLiveQuery((q) =>
37 q.from({ todo: todoCollection }).where(({ todo }) => todo.completed)
38 )
39​
40 const complete = (todo) => {
41 // Instantly applies optimistic state
42 todoCollection.update(todo.id, (draft) => {
43 draft.completed = true
44 })
45 }
46​
47 return (
48 <ul>
49 {todos.map((todo) => (
50 <li key={todo.id} onClick={() => complete(todo)}>
51 {todo.text}
52 </li>
53 ))}
54 </ul>
55 )
57```
58​
59### Defining collections
60​
61Collections are typed sets of objects that can be populated with data. They're designed to de-couple loading data into your app from binding data to your components.
62​
63Collections can be populated in many ways, including:
64​
65- fetching data, for example [from API endpoints using TanStack Query](https://tanstack.com/query/latest)
66- syncing data, for example [using a sync engine like ElectricSQL](https://electric-sql.com/)
67- storing local data, for example [using localStorage for user preferences and settings](#localstoragecollection) or [in-memory client data or UI state](#localonlycollection)
68- from live collection queries, creating [derived collections as materialised views](#using-live-queries)
69​
70Once you have your data in collections, you can query across them using live queries in your components.
71​
72### Using live queries
73​
74Live queries are used to query data out of collections. Live queries are reactive: when the underlying data changes in a way that would affect the query result, the result is incrementally updated and returned from the query, triggering a re-render.
75​
76TanStack DB live queries are implemented using [d2ts](https://github.com/electric-sql/d2ts), a Typescript implementation of differential dataflow. This allows the query results to update _incrementally_ (rather than by re-running the whole query). This makes them blazing fast, usually sub-millisecond, even for highly complex queries.
77​
78Live queries support joins across collections. This allows you to:
79​
801. load normalised data into collections and then de-normalise it through queries; simplifying your backend by avoiding the need for bespoke API endpoints that match your client
812. join data from multiple sources; for example, syncing some data out of a database, fetching some other data from an external API and then joining these into a unified data model for your front-end code
82​
83Every query returns another collection which can _also_ be queried.
84​
85For more details on live queries, see the [Live Queries](../guides/live-queries.md) documentation.
86​
87### Making optimistic mutations
88​
89Collections support `insert`, `update` and `delete` operations. When called, by default they trigger the corresponding `onInsert`, `onUpdate`, `onDelete` handlers which are responsible for writing the mutation to the backend.
90​
91```ts
92// Define collection with persistence handlers
93const todoCollection = createCollection({
94 id: "todos",
95 // ... other config
96 onUpdate: async ({ transaction }) => {
97 const { original, changes } = transaction.mutations[0]
98 await api.todos.update(original.id, changes)
99 },
100})
101​
102// Immediately applies optimistic state
103todoCollection.update(todo.id, (draft) => {
104 draft.completed = true
105})
106```
107​
108The collection maintains optimistic state separately from synced data. When live queries read from the collection, they see a local view that overlays the optimistic mutations on top of the immutable synced data.
109​
110The optimistic state is held until the handler resolves, at which point the data is persisted to the server and synced back. If the handler throws an error, the optimistic state is rolled back.
111​
112For more complex mutations, you can create custom actions with `createOptimisticAction` or custom transactions with `createTransaction`. See the [Mutations guide](../guides/mutations.md) for details.
113​
114### Uni-directional data flow
115​
116This combines to support a model of uni-directional data flow, extending the redux/flux style state management pattern beyond the client, to take in the server as well:
117​
118<figure>
119 <a href="https://raw.githubusercontent.com/TanStack/db/main/docs/unidirectional-data-flow.lg.png" target="_blank">
120 <img src="https://raw.githubusercontent.com/TanStack/db/main/docs/unidirectional-data-flow.png" />
121 </a>
122</figure>
123​
124With an instant inner loop of optimistic state, superseded in time by the slower outer loop of persisting to the server and syncing the updated server state back into the collection.
125​
126## API reference
127​
128### Collections
129​
130There are a number of built-in collection types:
131​
1321. [`QueryCollection`](#querycollection) to load data into collections using [TanStack Query](https://tanstack.com/query)
1332. [`ElectricCollection`](#electriccollection) to sync data into collections using [ElectricSQL](https://electric-sql.com)
1343. [`TrailBaseCollection`](#trailbasecollection) to sync data into collections using [TrailBase](https://trailbase.io)
1354. [`RxDBCollection`](#rxdbcollection) to integrate with [RxDB](https://rxdb.info) for local persistence and sync
1365. [`LocalStorageCollection`](#localstoragecollection) for small amounts of local-only state that syncs across browser tabs
1376. [`LocalOnlyCollection`](#localonlycollection) for in-memory client data or UI state
138​
139You can also use:
140​
141- use live collection queries to [derive collections from other collections](#derived-collections)
142- the [base Collection](#base-collection) to define your own collection types
143​
144#### Collection schemas
145​
146All collections optionally (though strongly recommended) support adding a `schema`.
147​
148If provided, this must be a [Standard Schema](https://standardschema.dev) compatible schema instance, such as a [Zod](https://zod.dev) or [Effect](https://effect.website/docs/schema/introduction/) schema.
149​
150The collection will use the schema to do client-side validation of optimistic mutations.
151​
152The collection will use the schema for its type so if you provide a schema, you can't also pass in an explicit
153type (e.g. `createCollection<Todo>()`).
154​
155#### `QueryCollection`
156​
157[TanStack Query](https://tanstack.com/query) fetches data using managed queries. Use `queryCollectionOptions` to fetch data into a collection using TanStack Query:
158​
159```ts
160import { createCollection } from "@tanstack/react-db"
161import { queryCollectionOptions } from "@tanstack/query-db-collection"
162​
163const todoCollection = createCollection(
164 queryCollectionOptions({
165 queryKey: ["todoItems"],
166 queryFn: async () => {
167 const response = await fetch("/api/todos")
168 return response.json()
169 },
170 getKey: (item) => item.id,
171 schema: todoSchema, // any standard schema
172 })
174```
175​
176The collection will be populated with the query results.
177​
178#### `ElectricCollection`
179​
180[Electric](https://electric-sql.com) is a read-path sync engine for Postgres. It allows you to sync subsets of data out of a Postgres database, [through your API](https://electric-sql.com/blog/2024/11/21/local-first-with-your-existing-api), into a TanStack DB collection.
181​
182Electric's main primitive for sync is a [Shape](https://electric-sql.com/docs/guides/shapes). Use `electricCollectionOptions` to sync a shape into a collection:
183​
184```ts
185import { createCollection } from "@tanstack/react-db"
186import { electricCollectionOptions } from "@tanstack/electric-db-collection"
187​
188export const todoCollection = createCollection(
189 electricCollectionOptions({
190 id: "todos",
191 shapeOptions: {
192 url: "https://example.com/v1/shape",
193 params: {
194 table: "todos",
195 },
196 },
197 getKey: (item) => item.id,
198 schema: todoSchema,
199 })
201```
202​
203The Electric collection requires two Electric-specific options:
204​
205- `shapeOptions` &mdash; the Electric [ShapeStreamOptions](https://electric-sql.com/docs/api/clients/typescript#options) that define the [Shape](https://electric-sql.com/docs/guides/shapes) to sync into the collection; this includes the
206 - `url` to your sync engine; and
207 - `params` to specify the `table` to sync and any optional `where` clauses, etc.
208- `getKey` &mdash; identifies the id for the rows being synced into the collection
209​
210A new collections doesn't start syncing until you call `collection.preload()` or you query it.
211​
212Electric shapes allow you to filter data using where clauses:
213​
214```ts
215export const myPendingTodos = createCollection(
216 electricCollectionOptions({
217 id: "todos",
218 shapeOptions: {
219 url: "https://example.com/v1/shape",
220 params: {
221 table: "todos",
222 where: `
223 status = 'pending'
224 AND
225 user_id = '${user.id}'
226 `,
227 },
228 },
229 getKey: (item) => item.id,
230 schema: todoSchema,
231 })
233```
234​
235> [!TIP]
236> Shape where clauses, used to filter the data you sync into `ElectricCollection`s, are different from the [live queries](#live-queries) you use to query data in components.
238> Live queries are much more expressive than shapes, allowing you to query across collections, join, aggregate, etc. Shapes just contain filtered database tables and are used to populate the data in a collection.
239​
240If you need more control over what data syncs into the collection, Electric allows you to [use your API](https://electric-sql.com/blog/2024/11/21/local-first-with-your-existing-api#filtering) as a proxy to both authorize and filter data.
241​
242See the [Electric docs](https://electric-sql.com/docs/intro) for more information.
243​
244#### `TrailBaseCollection`
245​
246[TrailBase](https://trailbase.io) is an easy-to-self-host, single-executable application backend with built-in SQLite, a V8 JS runtime, auth, admin UIs and sync functionality.
247​
248TrailBase lets you expose tables via [Record APIs](https://trailbase.io/documentation/apis_record/) and subscribe to changes when `enable_subscriptions` is set. Use `trailBaseCollectionOptions` to sync records into a collection:
249​
250```ts
251import { createCollection } from "@tanstack/react-db"
252import { trailBaseCollectionOptions } from "@tanstack/trailbase-db-collection"
253import { initClient } from "trailbase"
254​
255const trailBaseClient = initClient(`https://trailbase.io`)
256​
257export const todoCollection = createCollection<SelectTodo, Todo>(
258 trailBaseCollectionOptions({
259 id: "todos",
260 recordApi: trailBaseClient.records(`todos`),
261 getKey: (item) => item.id,
262 schema: todoSchema,
263 parse: {
264 created_at: (ts) => new Date(ts * 1000),
265 },
266 serialize: {
267 created_at: (date) => Math.floor(date.valueOf() / 1000),
268 },
269 })
271```
272​
273This collection requires the following TrailBase-specific options:
274​
275- `recordApi` — identifies the API to sync.
276- `getKey` — identifies the id for the records being synced into the collection.
277- `parse` — maps `(v: Todo[k]) => SelectTodo[k]`.
278- `serialize` — maps `(v: SelectTodo[k]) => Todo[k]`.
279​
280A new collections doesn't start syncing until you call `collection.preload()` or you query it.
281​
282#### `RxDBCollection`
283​
284[RxDB](https://rxdb.info) is a client-side database for JavaScript apps with replication, conflict resolution, and offline-first features.
285Use `rxdbCollectionOptions` from `@tanstack/rxdb-db-collection` to integrate an RxDB collection with TanStack DB:
286​
287```ts
288import { createCollection } from "@tanstack/react-db"
289import { rxdbCollectionOptions } from "@tanstack/rxdb-db-collection"
290import { createRxDatabase } from "rxdb"
291​
292const db = await createRxDatabase({
293 name: "mydb",
294 storage: getRxStorageMemory(),
295})
296await db.addCollections({
297 todos: {
298 schema: {
299 version: 0,
300 primaryKey: "id",
301 type: "object",
302 properties: {
303 id: { type: "string", maxLength: 100 },
304 text: { type: "string" },
305 completed: { type: "boolean" },
306 },
307 },
308 },
309})
310​
311// Wrap the RxDB collection with TanStack DB
312export const todoCollection = createCollection(
313 rxdbCollectionOptions({
314 rxCollection: db.todos,
315 startSync: true,
316 })
318```
319​
320With this integration:
321​
322- TanStack DB subscribes to RxDB's change streams and reflects updates, deletes, and inserts in real-time.
323- You get local-first sync when RxDB replication is configured.
324- Mutation handlers (onInsert, onUpdate, onDelete) are implemented using RxDB's APIs (bulkUpsert, incrementalPatch, bulkRemove).
325​
326This makes RxDB a great choice for apps that need local-first storage, replication, or peer-to-peer sync combined with TanStack DB's live queries and transaction lifecycle.
327​
328#### `LocalStorageCollection`
329​
330localStorage collections store small amounts of local-only state that persists across browser sessions and syncs across browser tabs in real-time. All data is stored under a single localStorage key and automatically synchronized using storage events.
331​
332Use `localStorageCollectionOptions` to create a collection that stores data in localStorage:
333​
334```ts
335import { createCollection } from "@tanstack/react-db"
336import { localStorageCollectionOptions } from "@tanstack/react-db"
337​
338export const userPreferencesCollection = createCollection(
339 localStorageCollectionOptions({
340 id: "user-preferences",
341 storageKey: "app-user-prefs", // localStorage key
342 getKey: (item) => item.id,
343 schema: userPrefsSchema,
344 })
346```
347​
348The localStorage collection requires:
349​
350- `storageKey` — the localStorage key where all collection data is stored
351- `getKey` — identifies the id for items in the collection
352​
353Mutation handlers (`onInsert`, `onUpdate`, `onDelete`) are completely optional. Data will persist to localStorage whether or not you provide handlers. You can provide alternative storage backends like `sessionStorage` or custom implementations that match the localStorage API.
354​
355```ts
356export const sessionCollection = createCollection(
357 localStorageCollectionOptions({
358 id: "session-data",
359 storageKey: "session-key",
360 storage: sessionStorage, // Use sessionStorage instead
361 getKey: (item) => item.id,
362 })
364```
365​
366> [!TIP]
367> localStorage collections are perfect for user preferences, UI state, and other data that should persist locally but doesn't need server synchronization. For server-synchronized data, use [`QueryCollection`](#querycollection) or [`ElectricCollection`](#electriccollection) instead.
368​
369#### `LocalOnlyCollection`
370​
371LocalOnly collections are designed for in-memory client data or UI state that doesn't need to persist across browser sessions or sync across tabs. They provide a simple way to manage temporary, session-only data with full optimistic mutation support.
372​
373Use `localOnlyCollectionOptions` to create a collection that stores data only in memory:
374​
375```ts
376import { createCollection } from "@tanstack/react-db"
377import { localOnlyCollectionOptions } from "@tanstack/react-db"
378​
379export const uiStateCollection = createCollection(
380 localOnlyCollectionOptions({
381 id: "ui-state",
382 getKey: (item) => item.id,
383 schema: uiStateSchema,
384 // Optional initial data to populate the collection
385 initialData: [
386 { id: "sidebar", isOpen: false },
387 { id: "theme", mode: "light" },
388 ],
389 })
391```
392​
393The LocalOnly collection requires:
394​
395- `getKey` — identifies the id for items in the collection
396​
397Optional configuration:
398​
399- `initialData` — array of items to populate the collection with on creation
400- `onInsert`, `onUpdate`, `onDelete` — optional mutation handlers for custom logic
401​
402Mutation handlers are completely optional. When provided, they are called before the optimistic state is confirmed. The collection automatically manages the transition from optimistic to confirmed state internally.
403​
404```ts
405export const tempDataCollection = createCollection(
406 localOnlyCollectionOptions({
407 id: "temp-data",
408 getKey: (item) => item.id,
409 onInsert: async ({ transaction }) => {
410 // Custom logic before confirming the insert
411 console.log("Inserting:", transaction.mutations[0].modified)
412 },
413 onUpdate: async ({ transaction }) => {
414 // Custom logic before confirming the update
415 const { original, modified } = transaction.mutations[0]
416 console.log("Updating from", original, "to", modified)
417 },
418 })
420```
421​
422> [!TIP]
423> LocalOnly collections are perfect for temporary UI state, form data, or any client-side data that doesn't need persistence. For data that should persist across sessions, use [`LocalStorageCollection`](#localstoragecollection) instead.
424​
425#### Derived collections
426​
427Live queries return collections. This allows you to derive collections from other collections.
428​
429For example:
430​
431```ts
432import { createLiveQueryCollection, eq } from "@tanstack/db"
433​
434// Imagine you have a collection of todos.
435const todoCollection = createCollection({
436 // config
437})
438​
439// You can derive a new collection that's a subset of it.
440const completedTodoCollection = createLiveQueryCollection({
441 startSync: true,
442 query: (q) =>
443 q.from({ todo: todoCollection }).where(({ todo }) => todo.completed),
444})
445```
446​
447This also works with joins to derive collections from multiple source collections. And it works recursively -- you can derive collections from other derived collections. Changes propagate efficiently using differential dataflow and it's collections all the way down.
448​
449#### Collection
450​
451There is a `Collection` interface in [`../packages/db/src/collection.ts`](https://github.com/TanStack/db/blob/main/packages/db/src/collection.ts). You can use this to implement your own collection types.
452​
453See the existing implementations in [`../packages/db`](https://github.com/TanStack/db/tree/main/packages/db), [`../packages/query-db-collection`](https://github.com/TanStack/db/tree/main/packages/query-db-collection), [`../packages/electric-db-collection`](https://github.com/TanStack/db/tree/main/packages/electric-db-collection) and [`../packages/trailbase-db-collection`](https://github.com/TanStack/db/tree/main/packages/trailbase-db-collection) for reference.
454​
455### Live queries
456​
457#### `useLiveQuery` hook
458​
459Use the `useLiveQuery` hook to assign live query results to a state variable in your React components:
460​
461```ts
462import { useLiveQuery } from '@tanstack/react-db'
463import { eq } from '@tanstack/db'
464​
465const Todos = () => {
466 const { data: todos } = useLiveQuery((q) =>
467 q
468 .from({ todo: todoCollection })
469 .where(({ todo }) => eq(todo.completed, false))
470 .orderBy(({ todo }) => todo.created_at, 'asc')
471 .select(({ todo }) => ({
472 id: todo.id,
473 text: todo.text
474 }))
475 )
476​
477 return <List items={ todos } />
479```
480​
481You can also query across collections with joins:
482​
483```ts
484import { useLiveQuery } from '@tanstack/react-db'
485import { eq } from '@tanstack/db'
486​
487const Todos = () => {
488 const { data: todos } = useLiveQuery((q) =>
489 q
490 .from({ todos: todoCollection })
491 .join(
492 { lists: listCollection },
493 ({ todos, lists }) => eq(lists.id, todos.listId),
494 'inner'
495 )
496 .where(({ lists }) => eq(lists.active, true))
497 .select(({ todos, lists }) => ({
498 id: todos.id,
499 title: todos.title,
500 listName: lists.name
501 }))
502 )
503​
504 return <List items={ todos } />
506```
507​
508#### `queryBuilder`
509​
510You can also build queries directly (outside of the component lifecycle) using the underlying `queryBuilder` API:
511​
512```ts
513import { createLiveQueryCollection, eq } from "@tanstack/db"
514​
515const completedTodos = createLiveQueryCollection({
516 startSync: true,
517 query: (q) =>
518 q
519 .from({ todo: todoCollection })
520 .where(({ todo }) => eq(todo.completed, true)),
521})
522​
523const results = completedTodos.toArray
524```
525​
526Note also that:
527​
5281. the query results [are themselves a collection](#derived-collections)
5292. the `useLiveQuery` automatically starts and stops live query subscriptions when you mount and unmount your components; if you're creating queries manually, you need to manually manage the subscription lifecycle yourself
530​
531See the [Live Queries](../guides/live-queries.md) documentation for more details.
532​
533### Transactional mutators
534​
535For more complex mutations beyond simple CRUD operations, TanStack DB provides `createOptimisticAction` and `createTransaction` for creating custom mutations with full control over the mutation lifecycle.
536​
537See the [Mutations guide](../guides/mutations.md) for comprehensive documentation on:
538​
539- Creating custom actions with `createOptimisticAction`
540- Manual transactions with `createTransaction`
541- Mutation merging behavior
542- Controlling optimistic vs non-optimistic updates
543- Handling temporary IDs
544- Transaction lifecycle states
545​
546## Usage examples
547​
548Here we illustrate two common ways of using TanStack DB:
549​
5501. [using TanStack Query](#1-tanstack-query) with an existing REST API
5512. [using the ElectricSQL sync engine](#2-electricsql-sync) with a generic ingestion endpoint
552​
553> [!TIP]
554> You can combine these patterns. One of the benefits of TanStack DB is that you can integrate different ways of loading data and handling mutations into the same app. Your components don't need to know where the data came from or goes.
555​
556### 1. TanStack Query
557​
558You can use TanStack DB with your existing REST API via TanStack Query.
559​
560The steps are to:
561​
5621. create [`QueryCollection`](#querycollection)s that load data using TanStack Query
5632. implement [`mutationFn`](#mutationfn)s that handle mutations by posting them to your API endpoints
564​
565```tsx
566import { useLiveQuery, createCollection } from "@tanstack/react-db"
567import { queryCollectionOptions } from "@tanstack/query-db-collection"
568​
569// Load data into collections using TanStack Query.
570// It's common to define these in a `collections` module.
571const todoCollection = createCollection(
572 queryCollectionOptions({
573 queryKey: ["todos"],
574 queryFn: async () => fetch("/api/todos"),
575 getKey: (item) => item.id,
576 schema: todoSchema, // any standard schema
577 onInsert: async ({ transaction }) => {
578 const { changes: newTodo } = transaction.mutations[0]
579​
580 // Handle the local write by sending it to your API.
581 await api.todos.create(newTodo)
582 },
583 // also add onUpdate, onDelete as needed.
584 })
586const listCollection = createCollection(
587 queryCollectionOptions({
588 queryKey: ["todo-lists"],
589 queryFn: async () => fetch("/api/todo-lists"),
590 getKey: (item) => item.id,
591 schema: todoListSchema,
592 onInsert: async ({ transaction }) => {
593 const { changes: newTodo } = transaction.mutations[0]
594​
595 // Handle the local write by sending it to your API.
596 await api.todoLists.create(newTodo)
597 },
598 // also add onUpdate, onDelete as needed.
599 })
601​
602const Todos = () => {
603 // Read the data using live queries. Here we show a live
604 // query that joins across two collections.
605 const { data: todos } = useLiveQuery((q) =>
606 q
607 .from({ todo: todoCollection })
608 .join(
609 { list: listCollection },
610 ({ todo, list }) => eq(list.id, todo.list_id),
611 "inner"
612 )
613 .where(({ list }) => eq(list.active, true))
614 .select(({ todo, list }) => ({
615 id: todo.id,
616 text: todo.text,
617 status: todo.status,
618 listName: list.name,
619 }))
620 )
621​
622 // ...
624```
625​
626This pattern allows you to extend an existing TanStack Query application, or any application built on a REST API, with blazing fast, cross-collection live queries and local optimistic mutations with automatically managed optimistic state.
627​
628### 2. ElectricSQL sync
629​
630One of the most powerful ways of using TanStack DB is with a sync engine, for a fully local-first experience with real-time sync. This allows you to incrementally adopt sync into an existing app, whilst still handling writes with your existing API.
631​
632Here, we illustrate this pattern using [ElectricSQL](https://electric-sql.com) as the sync engine.
633​
634```tsx
635import type { Collection } from "@tanstack/db"
636import type {
637 MutationFn,
638 PendingMutation,
639 createCollection,
640} from "@tanstack/react-db"
641import { electricCollectionOptions } from "@tanstack/electric-db-collection"
642​
643export const todoCollection = createCollection(
644 electricCollectionOptions({
645 id: "todos",
646 schema: todoSchema,
647 // Electric syncs data using "shapes". These are filtered views
648 // on database tables that Electric keeps in sync for you.
649 shapeOptions: {
650 url: "https://api.electric-sql.cloud/v1/shape",
651 params: {
652 table: "todos",
653 },
654 },
655 getKey: (item) => item.id,
656 schema: todoSchema,
657 onInsert: async ({ transaction }) => {
658 const response = await api.todos.create(transaction.mutations[0].modified)
659​
660 return { txid: response.txid }
661 },
662 // You can also implement onUpdate, onDelete as needed.
663 })
665​
666const AddTodo = () => {
667 return (
668 <Button
669 onClick={() => todoCollection.insert({ text: "🔥 Make app faster" })}
670 />
671 )
673```
674​
675## React Native
676​
677When using TanStack DB with React Native, you need to install and configure a UUID generation library since React Native doesn't include crypto.randomUUID() by default.
678​
679Install the `react-native-random-uuid` package:
680​
681```bash
682npm install react-native-random-uuid
683```
684​
685Then import it at the entry point of your React Native app (e.g., in your `App.js` or `index.js`):
686​
687```javascript
688import "react-native-random-uuid"
689```
690​
691This polyfill provides the `crypto.randomUUID()` function that TanStack DB uses internally for generating unique identifiers.
692​
693## More info
694​
695If you have questions / need help using TanStack DB, let us know on the Discord or start a GitHub discussion:
696​
697- [`#db` channel in the TanStack discord](https://discord.gg/yjUNbvbraC)
698- [GitHub discussions](https://github.com/tanstack/db/discussions)