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

local-only-collection.md

326 lines8.9 KB

1---
2title: LocalOnly Collection
3---
4​
5LocalOnly collections are designed for in-memory client data or UI state that doesn't need to persist across browser sessions or sync across tabs.
6​
7## Overview
8​
9The `localOnlyCollectionOptions` allows you to create collections that:
10- Store data only in memory (no persistence)
11- Support optimistic updates with automatic rollback on errors
12- Provide optional initial data
13- Work perfectly for temporary UI state and session-only data
14- Automatically manage the transition from optimistic to confirmed state
15​
16## Installation
17​
18LocalOnly collections are included in the core TanStack DB package:
19​
20```bash
21npm install @tanstack/react-db
22```
23​
24## Basic Usage
25​
26```typescript
27import { createCollection } from '@tanstack/react-db'
28import { localOnlyCollectionOptions } from '@tanstack/react-db'
29​
30const uiStateCollection = createCollection(
31 localOnlyCollectionOptions({
32 id: 'ui-state',
33 getKey: (item) => item.id,
34 })
36```
37​
38### Direct Local Mutations
39​
40**Important:** LocalOnly collections work differently than server-synced collections. With LocalOnly collections, you **directly mutate state** by calling methods like `collection.insert()`, `collection.update()`, and `collection.delete()` — that's all you need to do. The changes are immediately applied to your local in-memory data.
41​
42This is different from collections that sync with a server (like Query Collection), where mutation handlers send data to a backend. With LocalOnly collections, everything stays local:
43​
44```typescript
45// Just call the methods directly - no server sync involved
46uiStateCollection.insert({ id: 'theme', mode: 'dark' })
47uiStateCollection.update('theme', (draft) => { draft.mode = 'light' })
48uiStateCollection.delete('theme')
49```
50​
51## Configuration Options
52​
53The `localOnlyCollectionOptions` function accepts the following options:
54​
55### Required Options
56​
57- `id`: Unique identifier for the collection
58- `getKey`: Function to extract the unique key from an item
59​
60### Optional Options
61​
62- `schema`: [Standard Schema](https://standardschema.dev) compatible schema (e.g., Zod, Effect) for client-side validation
63- `initialData`: Array of items to populate the collection with on creation
64- `onInsert`: Optional handler function called before confirming inserts
65- `onUpdate`: Optional handler function called before confirming updates
66- `onDelete`: Optional handler function called before confirming deletes
67​
68## Initial Data
69​
70Populate the collection with initial data on creation:
71​
72```typescript
73const uiStateCollection = createCollection(
74 localOnlyCollectionOptions({
75 id: 'ui-state',
76 getKey: (item) => item.id,
77 initialData: [
78 { id: 'sidebar', isOpen: false },
79 { id: 'theme', mode: 'light' },
80 { id: 'modal', visible: false },
81 ],
82 })
84```
85​
86## Mutation Handlers
87​
88Mutation handlers are **completely optional**. When provided, they are called before the optimistic state is confirmed:
89​
90```typescript
91const tempDataCollection = createCollection(
92 localOnlyCollectionOptions({
93 id: 'temp-data',
94 getKey: (item) => item.id,
95 onInsert: async ({ transaction }) => {
96 // Custom logic before confirming the insert
97 console.log('Inserting:', transaction.mutations[0].modified)
98 },
99 onUpdate: async ({ transaction }) => {
100 // Custom logic before confirming the update
101 const { original, modified } = transaction.mutations[0]
102 console.log('Updating from', original, 'to', modified)
103 },
104 onDelete: async ({ transaction }) => {
105 // Custom logic before confirming the delete
106 console.log('Deleting:', transaction.mutations[0].original)
107 },
108 })
110```
111​
112## Manual Transactions
113​
114When using LocalOnly collections with manual transactions (created via `createTransaction`), you must call `utils.acceptMutations()` to persist the changes:
115​
116```typescript
117import { createTransaction } from '@tanstack/react-db'
118​
119const localData = createCollection(
120 localOnlyCollectionOptions({
121 id: 'form-draft',
122 getKey: (item) => item.id,
123 })
125​
126const serverCollection = createCollection(
127 queryCollectionOptions({
128 queryKey: ['items'],
129 queryFn: async () => api.items.getAll(),
130 getKey: (item) => item.id,
131 onInsert: async ({ transaction }) => {
132 await api.items.create(transaction.mutations[0].modified)
133 },
134 })
136​
137const tx = createTransaction({
138 mutationFn: async ({ transaction }) => {
139 // Handle server collection mutations explicitly in mutationFn
140 await Promise.all(
141 transaction.mutations
142 .filter((m) => m.collection === serverCollection)
143 .map((m) => api.items.create(m.modified))
144 )
145​
146 // After server mutations succeed, accept local collection mutations
147 localData.utils.acceptMutations(transaction)
148 },
149})
150​
151// Apply mutations to both collections in one transaction
152tx.mutate(() => {
153 localData.insert({ id: 'draft-1', data: '...' })
154 serverCollection.insert({ id: '1', name: 'Item' })
155})
156​
157await tx.commit()
158```
159​
160## Complete Example: Modal State Management
161​
162```typescript
163import { createCollection, eq } from '@tanstack/react-db'
164import { localOnlyCollectionOptions } from '@tanstack/react-db'
165import { useLiveQuery } from '@tanstack/react-db'
166import { z } from 'zod'
167​
168// Define schema
169const modalStateSchema = z.object({
170 id: z.string(),
171 isOpen: z.boolean(),
172 data: z.any().optional(),
173})
174​
175type ModalState = z.infer<typeof modalStateSchema>
176​
177// Create collection
178export const modalStateCollection = createCollection(
179 localOnlyCollectionOptions({
180 id: 'modal-state',
181 getKey: (item) => item.id,
182 schema: modalStateSchema,
183 initialData: [
184 { id: 'user-profile', isOpen: false },
185 { id: 'settings', isOpen: false },
186 { id: 'confirm-delete', isOpen: false },
187 ],
188 })
190​
191// Use in component
192function UserProfileModal() {
193 const { data: modals } = useLiveQuery({
194 query: (q) =>
195 q
196 .from({ modal: modalStateCollection })
197 .where(({ modal }) => eq(modal.id, 'user-profile')),
198 })
199​
200 const modalState = modals[0]
201​
202 const openModal = (data?: any) => {
203 modalStateCollection.update('user-profile', (draft) => {
204 draft.isOpen = true
205 draft.data = data
206 })
207 }
208​
209 const closeModal = () => {
210 modalStateCollection.update('user-profile', (draft) => {
211 draft.isOpen = false
212 draft.data = undefined
213 })
214 }
215​
216 if (!modalState?.isOpen) return null
217​
218 return (
219 <div className="modal">
220 <h2>User Profile</h2>
221 <pre>{JSON.stringify(modalState.data, null, 2)}</pre>
222 <button onClick={closeModal}>Close</button>
223 </div>
224 )
226```
227​
228## Complete Example: Form Draft State
229​
230```typescript
231import { createCollection, eq } from '@tanstack/react-db'
232import { localOnlyCollectionOptions } from '@tanstack/react-db'
233import { useLiveQuery } from '@tanstack/react-db'
234​
235type FormDraft = {
236 id: string
237 formData: Record<string, any>
238 lastModified: Date
240​
241// Create collection for form drafts
242export const formDraftsCollection = createCollection(
243 localOnlyCollectionOptions({
244 id: 'form-drafts',
245 getKey: (item) => item.id,
246 })
248​
249// Use in component
250function CreatePostForm() {
251 const { data: drafts } = useLiveQuery({
252 query: (q) =>
253 q
254 .from({ draft: formDraftsCollection })
255 .where(({ draft }) => eq(draft.id, 'new-post')),
256 })
257​
258 const currentDraft = drafts[0]
259​
260 const updateDraft = (field: string, value: any) => {
261 if (currentDraft) {
262 formDraftsCollection.update('new-post', (draft) => {
263 draft.formData[field] = value
264 draft.lastModified = new Date()
265 })
266 } else {
267 formDraftsCollection.insert({
268 id: 'new-post',
269 formData: { [field]: value },
270 lastModified: new Date(),
271 })
272 }
273 }
274​
275 const clearDraft = () => {
276 if (currentDraft) {
277 formDraftsCollection.delete('new-post')
278 }
279 }
280​
281 const submitForm = async () => {
282 if (!currentDraft) return
283​
284 await api.posts.create(currentDraft.formData)
285 clearDraft()
286 }
287​
288 return (
289 <form onSubmit={(e) => { e.preventDefault(); submitForm() }}>
290 <input
291 value={currentDraft?.formData.title || ''}
292 onChange={(e) => updateDraft('title', e.target.value)}
293 />
294 <button type="submit">Publish</button>
295 <button type="button" onClick={clearDraft}>Clear Draft</button>
296 </form>
297 )
299```
300​
301## Use Cases
302​
303LocalOnly collections are perfect for:
304- Temporary UI state (modals, sidebars, tooltips)
305- Form draft data during the current session
306- Client-side computed or derived data
307- Wizard/multi-step form state
308- Temporary filters or search state
309- In-memory caches
310​
311## Comparison with LocalStorageCollection
312​
313| Feature | LocalOnly | LocalStorage |
314|---------|-----------|--------------|
315| Persistence | None (in-memory only) | localStorage |
316| Cross-tab sync | No | Yes |
317| Survives page reload | No | Yes |
318| Performance | Fastest | Fast |
319| Size limits | Memory limits | ~5-10MB |
320| Best for | Temporary UI state | User preferences |
321​
322## Learn More
323​
324- [Optimistic Mutations](../guides/mutations.md)
325- [Live Queries](../guides/live-queries.md)
326- [LocalStorage Collection](./local-storage-collection.md)