Skip to content

bug: useQuery executes queries twice on component mount #1197

Open

Description

@WolverinDEV

When a component using useQuery from @powersync/tanstack-react-query is mounted, the query is executed twice:

  1. Initial execution
    The query runs because no cached result exists in the TanStack Query cache.
  2. Immediate invalidation
    The triggerImmediate option immediately invalidates the query, triggering a second execution even though the result was just fetched.
    I assume triggerImmediate was introduced to handle cases where the underlying table may have changed while the component was unmounted, making the cached query result stale.

Proposed solution
Instead of using triggerImmediate, I would suggest setting TanStack Query's refetchOnMount option to "always".
This should ensure that previously cached queries are refetched when the component mounts, while avoiding the redundant execution when no cached result exists.

Activity

  1. shahjahanpak commented on Nov 11, 2026

    @shahjahanpak

    I looked at this to see if I could send a fix, and I think triggerImmediate is doing a second job that refetchOnMount: 'always' would not cover.

    In usePowerSyncQueries, the query runs as soon as the component mounts, but the change listener is registered only after resolveTables() returns, which is async. A write to those tables that lands between the first read and the registration would not trigger anything, so the component would keep the old rows until the next write. The immediate trigger closes that gap, and it also refreshes cached data on remount when staleTime is long.

    So dropping it trades the extra query for possibly stale data. One direction I can see: hold the first fetch until the listener is registered, so the immediate invalidation is only needed when cached data already exists at mount. The cost is that the query stays pending a little longer on mount.

    Happy to send a PR for that or another direction you prefer, or leave it if the extra query is an acceptable cost.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

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