DATE:
AUTHOR:
PowerSync Product Team
JavaScript Packages/Libraries

Query-Driven Sync for the PowerSync TanStack DB Collection

DATE:
AUTHOR: PowerSync Product Team

The @tanstack/powersync-db-collection package now supports TanStack DB's query-driven syncon-demand sync mode where the collection only loads the rows your active live queries need, rather than syncing the entire SQLite table into memory upfront.

This matters for large datasets. If a user's todos table has 50,000 rows but a given screen only shows the 20 todos for a specific list, eager mode (the default) still loads all 50,000 rows into the TanStack DB collection. With on-demand mode, the collection derives its data boundary from your live query predicates, so only the relevant rows ever enter memory.

Two new data loading hooks — onLoad and onLoadSubset — let you go further and tie your Sync Stream subscriptions to the same boundary. That way you can control not just what moves from SQLite into TanStack DB, but what the PowerSync Service syncs into SQLite in the first place.

On-demand sync mode

Set syncMode: 'on-demand' on your collection. From then on, when a live query is registered, TanStack DB compiles its where clause into a SQLite expression and loads only the matching rows into the collection. When the query is deregistered, rows that are no longer needed by any active query are evicted.

const collection = createCollection(
  powerSyncCollectionOptions({
    database: db,
    table: AppSchema.props.todos,
    syncMode: 'on-demand',
  }),
)

const liveQuery = createLiveQueryCollection({
  query: (q) =>
    q
      .from({ todo: collection })
      .where(({ todo }) => eq(todo.list_id, selectedListId))
      .select(({ todo }) => ({ id: todo.id, completed: todo.completed })),
})

Sync Streams hooks

onLoad (eager mode) and onLoadSubset (on-demand mode) let you subscribe to a Sync Stream as part of the collection lifecycle. The subscription starts and stops automatically with the collection rather than needing to be managed separately. onLoadSubset is called whenever the active query set changes and receives the combined where expression, so you can derive your Sync Stream parameters directly from the query predicates rather than hardcoding them.

Getting started

Update to the latest version:

npm install @tanstack/powersync-db-collection@latest

Feedback and help

Share your feedback in the PowerSync Discord or on GitHub. We're particularly interested to learn about cases where on-demand mode doesn't currently handle a query predicate you need.

Powered by LaunchNotes