Skip to content
Source
Sign inSign up
TanStack/db

Add stable viewKey API to prevent UI re-renders during ID transitions #734

OpenKyleAMathewswants to merge 11 commits intomain fromclaude/review-issue-19-011CUdcC6qxdLp2AeFvUAuWdopened

Showing 6 changed files with 109 additions and 33 deletions (loading 3).

x
0 of 6 viewed, 6 left
31 additions and 0 deletions.changeset/stable-viewkeys-for-temp-ids.mdAdded
View file
@@ -0,0 +1,31 @@
+---
+"@tanstack/db": patch
+---
+​
+Add stable `viewKey` support to prevent UI re-renders during temporary-to-real ID transitions. When inserting items with temporary IDs that are later replaced by server-generated IDs, React components would previously unmount and remount, causing loss of focus and visual flicker.
+​
+Collections can now be configured with a `viewKey` function to generate stable keys:
+​
+```typescript
+const todoCollection = createCollection({
+ getKey: (item) => item.id,
+ viewKey: () => crypto.randomUUID(),
+ onInsert: async ({ transaction }) => {
+ const tempId = transaction.mutations[0].modified.id
+ const response = await api.create(...)
+​
+ // Link temporary and real IDs to same viewKey
+ todoCollection.mapViewKey(tempId, response.id)
+ await todoCollection.utils.refetch()
+ },
+})
+​
+// Use stable keys in React
+<li key={todoCollection.getViewKey(todo.id)}>
+```
+​
+New APIs:
+​
+- `collection.getViewKey(key)` - Returns stable viewKey for any key (temporary or real)
+- `collection.mapViewKey(tempKey, realKey)` - Links temporary and real IDs to share the same viewKey