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

local-only-collection.md

353 lines10.1 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. It loads when the Collection starts empty: at creation, or after cleanup. `reload()` keeps the rows, including your writes; the rows are the only copy of them.
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## Storable Values
69​
70A local-only Collection keeps rows in memory and never serializes them. A row
71can hold values that a persisted Collection cannot store, such as functions.
72The Collection returns such a value unchanged, with the same identity, after
73inserts and updates. See [Mutations](../guides/mutations.md) for how drafts
74copy plain objects and keep class instances by reference.
75​
76```typescript
77const handlers = createCollection(
78 localOnlyCollectionOptions({
79 getKey: (item) => item.id,
80 }),
82​
83handlers.insert({ id: 'save', run: () => console.log('saved') })
84handlers.get('save')?.run() // logs "saved"
85```
86​
87Nothing survives a page reload. If you might move these rows to
88[LocalStorageCollection](./local-storage-collection.md) or
89[IndexedDB](./indexed-db-collection.md) later, keep rows as plain data and look
90up behavior outside the row. Those Collections reject values they cannot store.
91​
92## Initial Data
93​
94Populate the collection with initial data on creation:
95​
96```typescript
97const uiStateCollection = createCollection(
98 localOnlyCollectionOptions({
99 id: 'ui-state',
100 getKey: (item) => item.id,
101 initialData: [
102 { id: 'sidebar', isOpen: false },
103 { id: 'theme', mode: 'light' },
104 { id: 'modal', visible: false },
105 ],
106 })
108```
109​
110## Mutation Handlers
111​
112Mutation handlers are **completely optional**. When provided, they are called before the optimistic state is confirmed:
113​
114```typescript
115const tempDataCollection = createCollection(
116 localOnlyCollectionOptions({
117 id: 'temp-data',
118 getKey: (item) => item.id,
119 onInsert: async ({ transaction }) => {
120 // Custom logic before confirming the insert
121 console.log('Inserting:', transaction.mutations[0].modified)
122 },
123 onUpdate: async ({ transaction }) => {
124 // Custom logic before confirming the update
125 const { original, modified } = transaction.mutations[0]
126 console.log('Updating from', original, 'to', modified)
127 },
128 onDelete: async ({ transaction }) => {
129 // Custom logic before confirming the delete
130 console.log('Deleting:', transaction.mutations[0].original)
131 },
132 })
134```
135​
136## Manual Transactions
137​
138When using LocalOnly collections with manual transactions (created via `createTransaction`), you must call `utils.acceptMutations()` to persist the changes:
139​
140```typescript
141import { createTransaction } from '@tanstack/react-db'
142​
143const localData = createCollection(
144 localOnlyCollectionOptions({
145 id: 'form-draft',
146 getKey: (item) => item.id,
147 })
149​
150const serverCollection = createCollection(
151 queryCollectionOptions({
152 queryKey: ['items'],
153 queryFn: async () => api.items.getAll(),
154 getKey: (item) => item.id,
155 onInsert: async ({ transaction }) => {
156 await api.items.create(transaction.mutations[0].modified)
157 },
158 })
160​
161const tx = createTransaction({
162 mutationFn: async ({ transaction }) => {
163 // Handle server collection mutations explicitly in mutationFn
164 await Promise.all(
165 transaction.mutations
166 .filter((m) => m.collection === serverCollection)
167 .map((m) => api.items.create(m.modified))
168 )
169​
170 // After server mutations succeed, accept local collection mutations
171 localData.utils.acceptMutations(transaction)
172 },
173})
174​
175// Apply mutations to both collections in one transaction
176tx.mutate(() => {
177 localData.insert({ id: 'draft-1', data: '...' })
178 serverCollection.insert({ id: '1', name: 'Item' })
179})
180​
181await tx.commit()
182```
183​
184## Complete Example: Modal State Management
185​
186```typescript
187import { createCollection, eq } from '@tanstack/react-db'
188import { localOnlyCollectionOptions } from '@tanstack/react-db'
189import { useLiveQuery } from '@tanstack/react-db'
190import { z } from 'zod'
191​
192// Define schema
193const modalStateSchema = z.object({
194 id: z.string(),
195 isOpen: z.boolean(),
196 data: z.any().optional(),
197})
198​
199type ModalState = z.infer<typeof modalStateSchema>
200​
201// Create collection
202export const modalStateCollection = createCollection(
203 localOnlyCollectionOptions({
204 id: 'modal-state',
205 getKey: (item) => item.id,
206 schema: modalStateSchema,
207 initialData: [
208 { id: 'user-profile', isOpen: false },
209 { id: 'settings', isOpen: false },
210 { id: 'confirm-delete', isOpen: false },
211 ],
212 })
214​
215// Use in component
216function UserProfileModal() {
217 const { data: modals } = useLiveQuery({
218 query: (q) =>
219 q
220 .from({ modal: modalStateCollection })
221 .where(({ modal }) => eq(modal.id, 'user-profile')),
222 })
223​
224 const modalState = modals[0]
225​
226 const openModal = (data?: any) => {
227 modalStateCollection.update('user-profile', (draft) => {
228 draft.isOpen = true
229 draft.data = data
230 })
231 }
232​
233 const closeModal = () => {
234 modalStateCollection.update('user-profile', (draft) => {
235 draft.isOpen = false
236 draft.data = undefined
237 })
238 }
239​
240 if (!modalState?.isOpen) return null
241​
242 return (
243 <div className="modal">
244 <h2>User Profile</h2>
245 <pre>{JSON.stringify(modalState.data, null, 2)}</pre>
246 <button onClick={closeModal}>Close</button>
247 </div>
248 )
250```
251​
252## Complete Example: Form Draft State
253​
254```typescript
255import { createCollection, eq } from '@tanstack/react-db'
256import { localOnlyCollectionOptions } from '@tanstack/react-db'
257import { useLiveQuery } from '@tanstack/react-db'
258​
259type FormDraft = {
260 id: string
261 formData: Record<string, any>
262 lastModified: Date
264​
265// Create collection for form drafts
266export const formDraftsCollection = createCollection(
267 localOnlyCollectionOptions({
268 id: 'form-drafts',
269 getKey: (item) => item.id,
270 })
272​
273// Use in component
274function CreatePostForm() {
275 const { data: drafts } = useLiveQuery({
276 query: (q) =>
277 q
278 .from({ draft: formDraftsCollection })
279 .where(({ draft }) => eq(draft.id, 'new-post')),
280 })
281​
282 const currentDraft = drafts[0]
283​
284 const updateDraft = (field: string, value: any) => {
285 if (currentDraft) {
286 formDraftsCollection.update('new-post', (draft) => {
287 draft.formData[field] = value
288 draft.lastModified = new Date()
289 })
290 } else {
291 formDraftsCollection.insert({
292 id: 'new-post',
293 formData: { [field]: value },
294 lastModified: new Date(),
295 })
296 }
297 }
298​
299 const clearDraft = () => {
300 if (currentDraft) {
301 formDraftsCollection.delete('new-post')
302 }
303 }
304​
305 const submitForm = async () => {
306 if (!currentDraft) return
307​
308 await api.posts.create(currentDraft.formData)
309 clearDraft()
310 }
311​
312 return (
313 <form onSubmit={(e) => { e.preventDefault(); submitForm() }}>
314 <input
315 value={currentDraft?.formData.title || ''}
316 onChange={(e) => updateDraft('title', e.target.value)}
317 />
318 <button type="submit">Publish</button>
319 <button type="button" onClick={clearDraft}>Clear Draft</button>
320 </form>
321 )
323```
324​
325## Use Cases
326​
327LocalOnly collections are perfect for:
328- Temporary UI state (modals, sidebars, tooltips)
329- Form draft data during the current session
330- Client-side computed or derived data
331- Wizard/multi-step form state
332- Temporary filters or search state
333- In-memory caches
334​
335## Comparison with LocalStorageCollection
336​
337| Feature | LocalOnly | LocalStorage |
338|---------|-----------|--------------|
339| Persistence | None (in-memory only) | localStorage |
340| Cross-tab sync | No | Yes |
341| Survives page reload | No | Yes |
342| Performance | Fastest | Fast |
343| Size limits | Memory limits | ~5-10MB |
344| Row values | Any JavaScript value | Values the configured `parser` can store (JSON by default) |
345| Best for | Temporary UI state | User preferences |
346​
347## Learn More
348​
349- [IndexedDB Collection](./indexed-db-collection.md)
350​
351- [Optimistic Mutations](../guides/mutations.md)
352- [Live Queries](../guides/live-queries.md)
353- [LocalStorage Collection](./local-storage-collection.md)