Maintaining subscriptions to queries

When the last component subscribed to a given Convex query unmounts that subscription can be dropped. But it's often useful to keep that subscription around for while.

For non-Convex query function the React Query option gcTime is the length of time to hold on to a stale result before dropping it out of cache. Convex queries use the same parameter to mean how long to stay subscribed to the query. This way Convex query results are always consistent, are never stale.

to see these query subscriptions stick around as you click between chat channels. These queries use a gcTime of 10 seconds. If you want subscriptions to be dropped immediately use a gcTime of 0.

The default gcTime in React Query is five minutes and this is not currently overridden in the Convex query options factories like convexQuery(), but this may change in future versions of the integration. You can always override this value by spreading the query options into a new options object.

Since client-side navigations in TanStack Start preserve the Query Client, these query subscriptions remain active from previous pages as well. When debugging why data is loaded or not it's good to keep this in mind. To get more prescriptive about data being available ahead of time you might add the query to a loader.

1import { useQuery } from "@tanstack/react-query";
2import { convexQuery } from "@convex-dev/react-query";
3import { api } from "../convex/_generated/api";
4
5const { data, isPending } = useQuery({
6 // spread query options to add more or override
7 ...convexQuery(
8 api.messages.listMessages,
9 { channel: "chatty" }
10 ),
11 gcTime: 2000 // 2 seconds
12});