Realtime updates
When the server pushes events over a WebSocket or Server-Sent Events, the cache is where they should land: every component reading the affected query re-renders, and nothing else needs to know a socket exists. This recipe connects Builder's typed WebSocket and SSE subscriptions to a query's setData and invalidate.
Write or invalidate
Each event leads to one of two cache operations:
- The event carries the new data. Write it with
setData. No request is made. - The event only says something changed. Call
invalidate. Mounted queries refetch; the rest are marked stale and refetch when next used.
Lists usually get invalidate even when the event carries the item, because the event cannot tell you where the item belongs in every filtered and paginated variant you have cached.
From a WebSocket
Declare the connection and one subscription per topic. The payload schemas reuse what the HTTP endpoints already validate with.
Then bridge them to the cache in one hook, mounted once near the root of the app:
The handlers receive validated payloads: user has the type userQuery stores, so setData accepts it as is. A message that fails its schema is skipped and never reaches the cache; it is reported to the onError hook of socketBuilder.
From Server-Sent Events
The SSE builder has the same shape, with events in place of topics.
Updating part of an entry
An event often carries a fragment: a new item, a changed field. Pass setData a function; it receives the current value, typed, or undefined when nothing is cached.
Returning undefined for an empty entry leaves it empty, which is what you want: there is no point creating a partial entry that a later fetch would have to correct.
setData addresses exactly one entry, the one for the arguments you pass. To change every cached variant of a list, either invalidate the endpoint or use TanStack's queryClient.setQueriesData with usersQuery.key() as the filter.
After a reconnect
Events sent while the connection was down are lost, so cached data may be behind. A browser EventSource reconnects on its own; invalidate what the stream feeds each time it opens:
The first open after mounting triggers it too, which costs one refetch of the mounted queries. A declareWebSocket connection does not reconnect; when your code opens a new one, invalidate after provideClient.
Polling
When the server cannot push, poll. That is plain TanStack Query: pass refetchInterval, a number or a function of the query, in the hook's options.
See TanStack's useQuery reference for refetchInterval, refetchIntervalInBackground and refetchOnWindowFocus.