Repository navigation
Description
Versions: @powersync/react 2.2.0, @powersync/common 2.5.0, @powersync/web 2.6.0 (@powersync/shared-internals 1.5.0)
What happens
useQuery has no way to turn a query off. The usual workaround is to pass a constant no-op query (for example SELECT 0 WHERE 1=0) while the inputs are not ready, because hooks must always be called. That no-op still costs:
- Two SQL statements every time the watch is set up or its settings change.
linkQueryawaitsresolveTables, which runsEXPLAIN <sql>and thenSELECT DISTINCT tbl_name FROM sqlite_master WHERE rootpage IN (SELECT json_each.value FROM json_each(?)), even when EXPLAIN found no root pages. Both go through the read connections, so they queue in front of real reads. - A
tablesUpdatedlistener for the life of the watch. Every write burst adds names to the watch's set and starts a throttle timer, even though the watch depends on no table. - A
statusChangedsubscription. The component re-renders on every sync status change.
useQuery accepts a tables option in its type (SQLOnChangeOptions.tables), but resolveConfig, the WatchedQueryWork constructor and tryUpdate do not pass it on, so passing an explicit (or empty) table list does not skip resolution.
Why it matters
In a screen-heavy React app, most hooks on a page are often disabled: pickers that are closed, lookups waiting for an id, optional sections. In one of our screens about 110 of 150 watches were disabled. That is about 220 extra statements on every mount of the screen, plus one timer per disabled watch on every write burst, and one re-render per watch per status change. With many statements queued, each real read waited a median of ~170 ms for a connection while running in ~1 ms.
As a workaround we now own the watch ourselves (customQuery(...).watch() built only while enabled, closed when disabled). On the same app that cut a page reload from 292 to 121 statements and watch setups from 118 to 32.
Repro
function Item({ id }: { id: string | null }) {
// Disabled until an id exists, but still pays EXPLAIN + sqlite_master
// on mount and keeps listening to every write and status change.
const { data } = useQuery(id ? 'SELECT * FROM lists WHERE id = ?' : 'SELECT 0 WHERE 1=0', id ? [id] : [])
return null
}
// Render 100 <Item id={null} /> and count statements on the database:
// about 200 statements, none of which can return a row.Suggestions (any one helps)
- An
enabled?: booleanoption foruseQuery/useSuspenseQuery: whilefalse, create no watch and no status subscription and return a settled empty state; when it turnstrue, start from the initial loading state (isLoading: true) so callers never see a false empty result. - Honour the
tablesoption inuseQueryby passing it to the watch astriggerOnTables(and keep it acrossupdateSettings). - In
resolveTables, skip thesqlite_masterlookup whenEXPLAINyields no root pages.
Happy to provide more numbers or test a patch.
Activity