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

KyleAMathewscommented

Summary

Fixes #19

Adds built-in support for stable view keys that prevent UI flicker when optimistic inserts transition from temporary IDs to real server-generated IDs.

The Problem

When inserting items with temporary IDs (e.g., negative numbers) that are later replaced by real server IDs, React treats the key change as a component identity shift, causing:

  1. UI Flicker - Components unmount and remount, resetting state
  2. Lost Focus - Input fields lose focus during ID transition
  3. Visual Jank - Animations restart, scroll position resets

Previously, developers had to manually maintain an external mapping from IDs to stable keys.

The Solution

Collections can now be configured with a viewKey function to automatically generate and track stable keys:

const todoCollection = createCollection({
  getKey: (item) => item.id,
  viewKey: () => crypto.randomUUID(), // ← Auto-generate stable keys
  onInsert: async ({ transaction }) => {
    const tempId = transaction.mutations[0].modified.id
    const response = await api.create(...)

    // Link temp ID to real ID - they share the same viewKey
    todoCollection.mapViewKey(tempId, response.id)
    await todoCollection.utils.refetch()
  },
})

// Use stable keys in React - no more flicker!
{todos.map((todo) => (
  <li key={todoCollection.getViewKey(todo.id)}>
    {todo.text}
  </li>
))}

API

New Configuration Option

  • viewKey?: (item: T) => string - Function to generate stable view keys for inserted items

New Collection Methods

  • getViewKey(key: TKey): string - Returns stable viewKey for any key (temporary or real). Falls back to String(key) if no viewKey is configured.

  • mapViewKey(tempKey: TKey, realKey: TKey): void - Links temporary and real IDs to share the same stable viewKey

Type Changes

  • Added viewKey?: string to PendingMutation interface
  • Added viewKey?: string to ChangeMessage interface

Implementation Details

  1. Storage: Added viewKeyMap: Map<TKey, string> to CollectionStateManager to track stable keys
  2. Generation: ViewKeys are automatically generated during insert() if configured
  3. Linking: mapViewKey() creates bidirectional mapping from both temp and real IDs to the same viewKey
  4. Events: All change events (insert/update/delete) now include viewKey for subscribers
  5. Persistence: ViewKeys kept indefinitely (tiny memory overhead ~50 bytes per item)

Backward Compatibility

✅ Fully backward compatible - All changes are opt-in:

  • Collections without viewKey config work exactly as before
  • getViewKey() returns String(key) when no viewKey is configured
  • No breaking changes to existing APIs

Documentation

Updated /docs/guides/mutations.md to replace the manual workaround with the new built-in API, including:

  • Complete usage example
  • How it works explanation
  • Best practices

Design Decisions

  1. Opt-in via configuration - Only active when explicitly enabled
  2. Function instead of object - Simple viewKey: () => uuid() instead of { generate: () => uuid() }
  3. Explicit linking - Manual mapViewKey() call for reliability (vs auto-detection which would be fragile)
  4. Collection-level storage - ViewKeys stored in collection metadata, not polluting item data
  5. Indefinite retention - Mappings kept forever for consistency (negligible memory impact)

    1. changeset-bot[bot](GitHub profile, opens in a new tab)commented

      🦋 Changeset detected

      Latest commit: 518c98313fed0f050860b9275956d367454870d7

      The changes in this PR will be included in the next version bump.

      This PR includes changesets to release 12 packages
      NameType
      @tanstack/dbPatch
      @tanstack/angular-dbPatch
      @tanstack/electric-db-collectionPatch
      @tanstack/query-db-collectionPatch
      @tanstack/react-dbPatch
      @tanstack/rxdb-db-collectionPatch
      @tanstack/solid-dbPatch
      @tanstack/svelte-dbPatch
      @tanstack/trailbase-db-collectionPatch
      @tanstack/vue-dbPatch
      todosPatch
      @tanstack/db-example-react-todoPatch

      Not sure what this means? Click here to learn what changesets are.

      Click here if you're a maintainer who wants to add another changeset to this PR

    2. pkg-pr-new[bot](GitHub profile, opens in a new tab)commented
      More templates

      @tanstack/angular-db

      npm i https://pkg.pr.new/@tanstack/angular-db@734

      @tanstack/db

      npm i https://pkg.pr.new/@tanstack/db@734

      @tanstack/db-ivm

      npm i https://pkg.pr.new/@tanstack/db-ivm@734

      @tanstack/electric-db-collection

      npm i https://pkg.pr.new/@tanstack/electric-db-collection@734

      @tanstack/query-db-collection

      npm i https://pkg.pr.new/@tanstack/query-db-collection@734

      @tanstack/react-db

      npm i https://pkg.pr.new/@tanstack/react-db@734

      @tanstack/rxdb-db-collection

      npm i https://pkg.pr.new/@tanstack/rxdb-db-collection@734

      @tanstack/solid-db

      npm i https://pkg.pr.new/@tanstack/solid-db@734

      @tanstack/svelte-db

      npm i https://pkg.pr.new/@tanstack/svelte-db@734

      @tanstack/trailbase-db-collection

      npm i https://pkg.pr.new/@tanstack/trailbase-db-collection@734

      @tanstack/vue-db

      npm i https://pkg.pr.new/@tanstack/vue-db@734

      commit: 518c983

    3. github-actions[bot](GitHub profile, opens in a new tab)commented

      Size Change: +708 B (+0.84%)

      Total Size: 85 kB

      FilenameSizeChange
      ./packages/db/dist/esm/collection/index.js3.87 kB+642 B (+19.87%)🚨
      ./packages/db/dist/esm/collection/mutations.js2.57 kB+55 B (+2.18%)
      ./packages/db/dist/esm/collection/state.js3.81 kB+11 B (+0.29%)
      ℹ️ View Unchanged
      FilenameSize
      ./packages/db/dist/esm/collection/change-events.js1.63 kB
      ./packages/db/dist/esm/collection/changes.js1.01 kB
      ./packages/db/dist/esm/collection/events.js413 B
      ./packages/db/dist/esm/collection/indexes.js1.16 kB
      ./packages/db/dist/esm/collection/lifecycle.js1.8 kB
      ./packages/db/dist/esm/collection/subscription.js2.2 kB
      ./packages/db/dist/esm/collection/sync.js2.2 kB
      ./packages/db/dist/esm/deferred.js230 B
      ./packages/db/dist/esm/errors.js3.48 kB
      ./packages/db/dist/esm/event-emitter.js798 B
      ./packages/db/dist/esm/index.js1.62 kB
      ./packages/db/dist/esm/indexes/auto-index.js794 B
      ./packages/db/dist/esm/indexes/base-index.js835 B
      ./packages/db/dist/esm/indexes/btree-index.js2 kB
      ./packages/db/dist/esm/indexes/lazy-index.js1.21 kB
      ./packages/db/dist/esm/indexes/reverse-index.js577 B
      ./packages/db/dist/esm/local-only.js967 B
      ./packages/db/dist/esm/local-storage.js2.42 kB
      ./packages/db/dist/esm/optimistic-action.js294 B
      ./packages/db/dist/esm/proxy.js3.86 kB
      ./packages/db/dist/esm/query/builder/functions.js615 B
      ./packages/db/dist/esm/query/builder/index.js4.04 kB
      ./packages/db/dist/esm/query/builder/ref-proxy.js938 B
      ./packages/db/dist/esm/query/compiler/evaluators.js1.55 kB
      ./packages/db/dist/esm/query/compiler/expressions.js760 B
      ./packages/db/dist/esm/query/compiler/group-by.js2.04 kB
      ./packages/db/dist/esm/query/compiler/index.js2.21 kB
      ./packages/db/dist/esm/query/compiler/joins.js2.65 kB
      ./packages/db/dist/esm/query/compiler/order-by.js1.43 kB
      ./packages/db/dist/esm/query/compiler/select.js1.28 kB
      ./packages/db/dist/esm/query/ir.js785 B
      ./packages/db/dist/esm/query/live-query-collection.js404 B
      ./packages/db/dist/esm/query/live/collection-config-builder.js5.54 kB
      ./packages/db/dist/esm/query/live/collection-registry.js233 B
      ./packages/db/dist/esm/query/live/collection-subscriber.js2.11 kB
      ./packages/db/dist/esm/query/optimizer.js3.26 kB
      ./packages/db/dist/esm/scheduler.js1.29 kB
      ./packages/db/dist/esm/SortedMap.js1.24 kB
      ./packages/db/dist/esm/transactions.js3.05 kB
      ./packages/db/dist/esm/utils.js1.01 kB
      ./packages/db/dist/esm/utils/browser-polyfills.js365 B
      ./packages/db/dist/esm/utils/btree.js6.01 kB
      ./packages/db/dist/esm/utils/comparison.js754 B
      ./packages/db/dist/esm/utils/index-optimization.js1.73 kB
      compressed-size-action::db-package-size
    4. github-actions[bot](GitHub profile, opens in a new tab)commented

      Size Change: 0 B

      Total Size: 2.89 kB

      ℹ️ View Unchanged
      FilenameSize
      ./packages/react-db/dist/esm/index.js168 B
      ./packages/react-db/dist/esm/useLiveInfiniteQuery.js1.41 kB
      ./packages/react-db/dist/esm/useLiveQuery.js1.31 kB
      compressed-size-action::react-db-package-size
    5. Nit: i would rename mapViewKey to setViewKey or storeViewKey.

    6. kevin-dp(GitHub profile, opens in a new tab) approved these changes

      Overall looks good to me. Left a few minor comments that i would like to see addressed.

      @@ -450,3 +450,21 @@
      450450 return this.config.getKey(item)
      451451 }
      452452
      453+ /**
      454+ * Get a stable view key for a given item key.
      455+ * If viewKey configuration is enabled, returns the stable viewKey.
      456+ * Otherwise, returns the key as a string (backward compatible behavior).
      457+ *
      458+ * @param key - The item key to get the view key for
      459+ * @returns The stable view key as a string
      460+ *
      461+ * @example
      462+ * // Use in React components for stable keys during ID transitions
      463+ * {todos.map((todo) => (
      464+ * <li key={collection.getViewKey(todo.id)}>
      465+ * {todo.text}
      466+ * </li>
      467+ * ))}
      468+ */
      469+ public getViewKey(key: TKey): string {
      470+ const viewKey = this._state.viewKeyMap.get(key)
      kevin-dp(GitHub profile, opens in a new tab)commented

      This is a leaky abstraction. The caller (i.e. getViewKey) here should not be aware of the internal representation of the view keys. I'd prefer moving this getViewKey method to the CollectionStateManager and then here define a method that forwards the call:

      public getViewKey(key: TKey): string {
        return this._state.getViewKey(key)
      }
      @@ -451,2 +451,21 @@
      451451 }
      452452
      453+ /**
      454+ * Get a stable view key for a given item key.
      455+ * If viewKey configuration is enabled, returns the stable viewKey.
      456+ * Otherwise, returns the key as a string (backward compatible behavior).
      457+ *
      458+ * @param key - The item key to get the view key for
      459+ * @returns The stable view key as a string
      460+ *
      461+ * @example
      462+ * // Use in React components for stable keys during ID transitions
      463+ * {todos.map((todo) => (
      464+ * <li key={collection.getViewKey(todo.id)}>
      465+ * {todo.text}
      466+ * </li>
      467+ * ))}
      468+ */
      469+ public getViewKey(key: TKey): string {
      470+ const viewKey = this._state.viewKeyMap.get(key)
      471+ return viewKey ?? String(key)
      kevin-dp(GitHub profile, opens in a new tab)commented

      Keys are of type TKey = string | number. If we have no viewKey we turn the key into a string and use it as the viewKey. Is there any reason to have keys as string | number but viewKeys always as string? Would it make sense to also allow viewKeys to be of type string | number ?

      @@ -452,0 +476,21 @@
      476+ * This is used when server-generated IDs replace temporary client IDs.
      477+ *
      478+ * @param tempKey - The temporary key used during optimistic insert
      479+ * @param realKey - The real key assigned by the server
      480+ *
      481+ * @example
      482+ * // In your insert handler, link temp ID to real ID
      483+ * onInsert: async ({ transaction }) => {
      484+ * const mutation = transaction.mutations[0]
      485+ * const tempId = mutation.modified.id
      486+ *
      487+ * const response = await api.todos.create(mutation.modified)
      488+ * const realId = response.id
      489+ *
      490+ * // Link the IDs so they share the same viewKey
      491+ * collection.mapViewKey(tempId, realId)
      492+ *
      493+ * await collection.utils.refetch()
      494+ * }
      495+ */
      496+ public mapViewKey(tempKey: TKey, realKey: TKey): void {
      kevin-dp(GitHub profile, opens in a new tab)commented

      Also a leaky abstraction. Move this implementation to the CollectionStateManager and have this public method delegate the call to the state manager's method.

      @@ -50,3 +50,5 @@
      5050 public optimisticUpserts = new Map<TKey, TOutput>()
      5151 public optimisticDeletes = new Set<TKey>()
      5252
      53+ // ViewKey mapping for stable rendering keys across ID transitions
      54+ public viewKeyMap = new Map<TKey, string>()
      kevin-dp(GitHub profile, opens in a new tab)commented

      No need to describe the type of the data structure in the field's name, i'd simplify the name to viewKeys.

      @@ -176,3 +176,9 @@
      176176 }
      177177 const globalKey = this.generateGlobalKey(key, item)
      178178
      179+ // Generate viewKey if configured
      180+ let viewKey: string | undefined
      181+ if (this.config.viewKey) {
      182+ viewKey = this.config.viewKey(validatedData)
      183+ // Store viewKey mapping
      184+ this.state.viewKeyMap.set(key, viewKey)
      kevin-dp(GitHub profile, opens in a new tab)commented

      Leaky abstraction. If the data structure ever changes, this call needs to be changed too.

    7. samwilliscommented

      @KyleAMathews code all looks ok with @kevin-dp suggestions. I do however want a little time to mull over the api, I'm not sure if I'm 100% happy with it (I may turn out to be). Can we wait till tomorrow before merging so I have a little time to think about it.

      In brief, and absolutely not my final thoughts:

      1. it would be nice to use the actual PK when there is one.
      2. I think the view keys will grow un-bound even when using a collection that GC's rows.
      3. does this have any impact on persistence when that comes, do we need to persist the view keys (writing that out, I don't think we do...).
    8. I think the view keys will grow un-bound even when using a collection that GC's rows.

      We should clean these up when the collection is GCed. But also this only runs when something is optimistically inserted — so it'll be very rare that people will insert thousands of rows client-side & be using this system. If they do happen to hit this edge case where there's a memory leak, we can politely ask them to invent their own system that they can constrain the memory 😆

      does this have any impact on persistence when that comes, do we need to persist the view keys (writing that out, I don't think we do...).

      Hmm perhaps? Though this is more a problem for the offline transactions package which does persist optimistic mutations. That's an edge case though that doesn't seem particularly urgent to solve.

    9. samwillis reviewed

      OK, I'e slept on it and have a few more thoughts:

      The purpose of this is to remap server provided keys back to some sort of stable key that can persist through id transitions. This current design only works at the view layer, and is not providing a stable key through the live query layer - thats ok as the live query later has no concept of an update, only deletes and inserts, and so any change is always going to go through.

      It's important to note that this only works on the source collection ids, not any composite ids that have been generated by the query layer when performing joins.

      My main thought is that I don't seen the need to the viewKey config option where a user can provide a function to generate random stable ids. All that is needed is an api to map back to a previously client side generated stable id. I can think of two options here;

      This is very similar to what you have now, but without the generating of random uuids or similar.

      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(...)
      
          // Update the internal map that maps from the server provided id, back to the temp id
          todoCollection.mapStableKey(tempId, response.id)
          await todoCollection.utils.refetch()
        },
      })
      
      <li key={todoCollection.getStableKey(todo.id)}>
      // getStableKey will return the old temp id if there is one, otherwise it returns the value passed to it.

      Here we are just keeping a map of the new key back to the old key when the id is returned from the server. The user provided temp key is the "stable key" for the lifetime of the session, there is no need to generate "view keys" as uuids.

      @@ -50,3 +50,5 @@
      5050 public optimisticUpserts = new Map<TKey, TOutput>()
      5151 public optimisticDeletes = new Set<TKey>()
      5252
      53+ // ViewKey mapping for stable rendering keys across ID transitions
      54+ public viewKeyMap = new Map<TKey, string>()
      samwilliscommented

      needs to be emptied in the cleanup at the bottom of this manger class.

    10. KyleAMathews linked this to fix #19

Sign in to join this conversation.