Same query used multiple times
Context: The result of a query is used quite a lot of time within my React-Native app, in particular into mutliple screen and deep component tree leaves. This can happen quite a lot, as in React-Native with React-Navigation, compared to the Web, you can have a lot of screens already mounted within the navigation stack (infinite in theory). And those screens subscribes to the same convex query.
Question: In that scenario, what is the good practice?
Solution 1), juste write the convex query everywhere, but with the risk of multiplicating by quite much the websocket connections. Is this correct that everytime I write "useQuery" it opens a new connection, regardless if the same query and same args is called somewhere else?
Solution 2) Introduce somehow a singleton with a state management solution. Call one time the convex query, hydrate the app global state, and components subscribe to this global state. The drawback is that it is a bit cumbersome to introduce this global state that somehow duplicate the convex one.
Which solution should would you recommend to pick?
2 Replies
if you're using Convex's React client, we already handle this for you. There will only be one websocket connection (one per
<ConvexProvider>
), with all queries sharing that connection. Furthermore, if you actually do identical useQuery
calls, with the same arguments, the Convex client deduplicates these for you, so there is no extra data sent over the websocket.
Note the deduplication only happens if the query appears in multiple components at the same time. If a component is unloaded before a new one is loaded, the query might be re-sent (still on the same websocket). If you want the caching to persist across component unloading, you can use this https://www.youtube.com/watch?v=ZgxDlSUGpfEConvex
YouTube
Can your database do this? Ep. 1: Magic caching
A Next.js app with no query cache? Jank. One with a cache? No more jank, but now we need to deal with cache invalidation and application consistency. Ugh.
But with Convex's magic query cache, Convex's powerful subscriptions are cached, not merely values. So you get the best of both words.
Repository here:
https://github.com/jamwt/cached-dmv
...
Oh that's very clear. I had this video to watch in my todo list and forgot about it.
As always, Convex is keeping the bar level very high. Awesome product providing the best DX possible, and awesome support that replies super fast.
Many thanks and have a nice day @lee