Skip to content

useLiveQuery (react) triggers extra mount re-render when collection is already ready #690

@john-rtr

Description

@john-rtr
  • I've validated the bug against the latest version of DB packages

Describe the bug

useLiveQuery (from @tanstack/react-db) forces a React re-render on mount even when the local collection is already ready and no data has changed. Additionally, the returned data reference changes, which prevents relying on referential stability. At minimum, when nothing changes, the data object reference should remain stable.

To Reproduce

Reproduction is the following TestRerender component (local-only collection + live query with startSync: true):

import { useEffect, useRef } from 'react'
import z from 'zod'
import {
  createCollection,
  createLiveQueryCollection,
  localOnlyCollectionOptions,
  useLiveQuery
} from '@tanstack/react-db'

const collection = createCollection(
  localOnlyCollectionOptions({
    id: 'local',
    getKey: (item: { id: string }) => item.id,
    schema: z.object({ id: z.string(), value: z.string() }),
    initialData: [
      { id: 'a', value: 'x' },
      { id: 'a', value: 'y' }
    ]
  })
)

const liveQuery = createLiveQueryCollection({
  startSync: true,
  query: (q) => q.from({ item: collection })
})

console.log('LiveQuery status before render:', liveQuery.status)

export function TestRerender() {
  const { data } = useLiveQuery(liveQuery)

  const renderCountRef = useRef(0)
  renderCountRef.current += 1

  useEffect(() => {
    console.log('renderCount', renderCountRef.current)
    prevDataRef.current = data
  })

  return null
}

Expected behavior

  • If the collection is already ready and no data has changed, mounting useLiveQuery should not trigger an additional render beyond the initial React mount.
  • At minimum, the data object reference should remain stable if no data has changed.

Actual behavior

  • An extra render occurs on mount and the data reference changes even though no data has changed.

Environment

  • OS: macOS 15 (darwin 24.0.0)
  • Framework: React 19.0.0
  • @tanstack/db: 0.4.11
  • @tanstack/react-db: 0.1.31
  • Tooling: Vite 6.2.1, TypeScript 5.8.2

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions