TanStack Query WebSocket in React: typed live updates without polling
Polling is often the first solution for a live dashboard. Fetch every few seconds, update the screen, repeat.
It works, but it also creates unnecessary requests and leaves a gap between a server-side change and the next poll. When the backend already exposes a WebSocket, you can push events to the browser instead.
The important part is not opening the socket. It is keeping the socket, the HTTP snapshot, and the TanStack Query cache consistent.
I use three clear responsibilities:
TanStack Query loads and caches the current server state.
WebSocket delivers live events and client messages.
The application decides how each event changes the cache and how to recover after a disconnect.
This walkthrough uses React, TanStack Query, and tanstack-fetch.…