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

local-storage-collection.md

312 lines9.3 KB

1---
2title: LocalStorage Collection
3---
4​
5LocalStorage collections store small amounts of local-only state that persists across browser sessions and syncs across browser tabs in real-time.
6​
7## Overview
8​
9The `localStorageCollectionOptions` allows you to create collections that:
10- Persist data to localStorage (or sessionStorage)
11- Automatically sync across browser tabs using storage events
12- Support optimistic updates with automatic rollback on errors
13- Store all data under a single localStorage key
14- Work with any storage API that matches the localStorage interface
15​
16## Installation
17​
18LocalStorage 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 { localStorageCollectionOptions } from '@tanstack/react-db'
29​
30const userPreferencesCollection = createCollection(
31 localStorageCollectionOptions({
32 id: 'user-preferences',
33 storageKey: 'app-user-prefs',
34 getKey: (item) => item.id,
35 })
37```
38​
39### Direct Local Mutations
40​
41**Important:** LocalStorage collections work differently than server-synced collections. With LocalStorage 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 data and automatically persisted to localStorage.
42​
43This is different from collections that sync with a server (like Query Collection), where mutation handlers send data to a backend. With LocalStorage collections, everything stays local:
44​
45```typescript
46// Just call the methods directly - automatically persisted to localStorage
47userPreferencesCollection.insert({ id: 'theme', mode: 'dark' })
48userPreferencesCollection.update('theme', (draft) => { draft.mode = 'light' })
49userPreferencesCollection.delete('theme')
50```
51​
52## Configuration Options
53​
54The `localStorageCollectionOptions` function accepts the following options:
55​
56### Required Options
57​
58- `id`: Unique identifier for the collection
59- `storageKey`: The localStorage key where all collection data is stored
60- `getKey`: Function to extract the unique key from an item
61​
62### Optional Options
63​
64- `schema`: [Standard Schema](https://standardschema.dev) compatible schema (e.g., Zod, Effect) for client-side validation
65- `storage`: Custom storage implementation (defaults to `localStorage`). Can be `sessionStorage` or any object with the localStorage API
66- `storageEventApi`: Event API for subscribing to storage events (defaults to `window`). Enables custom cross-tab, cross-window, or cross-process synchronization
67- `onInsert`: Optional handler function called when items are inserted
68- `onUpdate`: Optional handler function called when items are updated
69- `onDelete`: Optional handler function called when items are deleted
70​
71## Cross-Tab Synchronization
72​
73LocalStorage collections automatically sync across browser tabs in real-time:
74​
75```typescript
76const settingsCollection = createCollection(
77 localStorageCollectionOptions({
78 id: 'settings',
79 storageKey: 'app-settings',
80 getKey: (item) => item.id,
81 })
83​
84// Changes in one tab are automatically reflected in all other tabs
85// This works automatically via storage events
86```
87​
88## Using SessionStorage
89​
90You can use `sessionStorage` instead of `localStorage` for session-only persistence:
91​
92```typescript
93const sessionCollection = createCollection(
94 localStorageCollectionOptions({
95 id: 'session-data',
96 storageKey: 'session-key',
97 storage: sessionStorage, // Use sessionStorage instead
98 getKey: (item) => item.id,
99 })
101```
102​
103## Custom Storage Backend
104​
105Provide any storage implementation that matches the localStorage API:
106​
107```typescript
108// Example: Custom storage wrapper with encryption
109const encryptedStorage = {
110 getItem(key: string) {
111 const encrypted = localStorage.getItem(key)
112 return encrypted ? decrypt(encrypted) : null
113 },
114 setItem(key: string, value: string) {
115 localStorage.setItem(key, encrypt(value))
116 },
117 removeItem(key: string) {
118 localStorage.removeItem(key)
119 },
121​
122const secureCollection = createCollection(
123 localStorageCollectionOptions({
124 id: 'secure-data',
125 storageKey: 'encrypted-key',
126 storage: encryptedStorage,
127 getKey: (item) => item.id,
128 })
130```
131​
132### Cross-Tab Sync with Custom Storage
133​
134The `storageEventApi` option (defaults to `window`) allows the collection to subscribe to storage events for cross-tab synchronization. A custom storage implementation can provide this API to enable custom cross-tab, cross-window, or cross-process sync:
135​
136```typescript
137// Example: Custom storage event API for cross-process sync
138const customStorageEventApi = {
139 addEventListener(event: string, handler: (e: StorageEvent) => void) {
140 // Custom event subscription logic
141 // Could be IPC, WebSocket, or any other mechanism
142 myCustomEventBus.on('storage-change', handler)
143 },
144 removeEventListener(event: string, handler: (e: StorageEvent) => void) {
145 myCustomEventBus.off('storage-change', handler)
146 },
148​
149const syncedCollection = createCollection(
150 localStorageCollectionOptions({
151 id: 'synced-data',
152 storageKey: 'data-key',
153 storage: customStorage,
154 storageEventApi: customStorageEventApi, // Custom event API
155 getKey: (item) => item.id,
156 })
158```
159​
160This enables synchronization across different contexts beyond just browser tabs, such as:
161- Cross-process communication in Electron apps
162- WebSocket-based sync across multiple browser windows
163- Custom IPC mechanisms in desktop applications
164​
165## Mutation Handlers
166​
167Mutation handlers are **completely optional**. Data will persist to localStorage whether or not you provide handlers:
168​
169```typescript
170const preferencesCollection = createCollection(
171 localStorageCollectionOptions({
172 id: 'preferences',
173 storageKey: 'user-prefs',
174 getKey: (item) => item.id,
175 // Optional: Add custom logic when preferences are updated
176 onUpdate: async ({ transaction }) => {
177 const { modified } = transaction.mutations[0]
178 console.log('Preference updated:', modified)
179 // Maybe send analytics or trigger other side effects
180 },
181 })
183```
184​
185## Manual Transactions
186​
187When using LocalStorage collections with manual transactions (created via `createTransaction`), you must call `utils.acceptMutations()` to persist the changes:
188​
189```typescript
190import { createTransaction } from '@tanstack/react-db'
191​
192const localData = createCollection(
193 localStorageCollectionOptions({
194 id: 'form-draft',
195 storageKey: 'draft-data',
196 getKey: (item) => item.id,
197 })
199​
200const serverCollection = createCollection(
201 queryCollectionOptions({
202 queryKey: ['items'],
203 queryFn: async () => api.items.getAll(),
204 getKey: (item) => item.id,
205 onInsert: async ({ transaction }) => {
206 await api.items.create(transaction.mutations[0].modified)
207 },
208 })
210​
211const tx = createTransaction({
212 mutationFn: async ({ transaction }) => {
213 // Handle server collection mutations explicitly in mutationFn
214 await Promise.all(
215 transaction.mutations
216 .filter((m) => m.collection === serverCollection)
217 .map((m) => api.items.create(m.modified))
218 )
219​
220 // After server mutations succeed, persist local collection mutations
221 localData.utils.acceptMutations(transaction)
222 },
223})
224​
225// Apply mutations to both collections in one transaction
226tx.mutate(() => {
227 localData.insert({ id: 'draft-1', data: '...' })
228 serverCollection.insert({ id: '1', name: 'Item' })
229})
230​
231await tx.commit()
232```
233​
234## Complete Example
235​
236```typescript
237import { createCollection, eq } from '@tanstack/react-db'
238import { localStorageCollectionOptions } from '@tanstack/react-db'
239import { useLiveQuery } from '@tanstack/react-db'
240import { z } from 'zod'
241​
242// Define schema
243const userPrefsSchema = z.object({
244 id: z.string(),
245 theme: z.enum(['light', 'dark', 'auto']),
246 language: z.string(),
247 notifications: z.boolean(),
248})
249​
250type UserPrefs = z.infer<typeof userPrefsSchema>
251​
252// Create collection
253export const userPreferencesCollection = createCollection(
254 localStorageCollectionOptions({
255 id: 'user-preferences',
256 storageKey: 'app-user-prefs',
257 getKey: (item) => item.id,
258 schema: userPrefsSchema,
259 })
261​
262// Use in component
263function SettingsPanel() {
264 const { data: prefs } = useLiveQuery({
265 query: (q) =>
266 q
267 .from({ pref: userPreferencesCollection })
268 .where(({ pref }) => eq(pref.id, 'current-user')),
269 })
270​
271 const currentPrefs = prefs[0]
272​
273 const updateTheme = (theme: 'light' | 'dark' | 'auto') => {
274 if (currentPrefs) {
275 userPreferencesCollection.update(currentPrefs.id, (draft) => {
276 draft.theme = theme
277 })
278 } else {
279 userPreferencesCollection.insert({
280 id: 'current-user',
281 theme,
282 language: 'en',
283 notifications: true,
284 })
285 }
286 }
287​
288 return (
289 <div>
290 <h2>Theme: {currentPrefs?.theme}</h2>
291 <button onClick={() => updateTheme('dark')}>Dark Mode</button>
292 <button onClick={() => updateTheme('light')}>Light Mode</button>
293 </div>
294 )
296```
297​
298## Use Cases
299​
300LocalStorage collections are perfect for:
301- User preferences and settings
302- UI state that should persist across sessions
303- Form drafts
304- Recently viewed items
305- User-specific configurations
306- Small amounts of cached data
307​
308## Learn More
309​
310- [Optimistic Mutations](../guides/mutations.md)
311- [Live Queries](../guides/live-queries.md)
312- [LocalOnly Collection](./local-only-collection.md)