Abbottabad, KPK
BlogJuly 8, 2026

Building Real-Time Notification Pipelines with WebSockets and TanStack Query

Haseeb Gul
When building interactive dashboards, live interpretation platforms, or fleet management tools, keeping the UI synchronized with instant backend state shifts is critical. Traditional polling approaches overload servers with redundant HTTP requests, while streaming massive database payloads over pure WebSockets creates state sync bugs and memory leaks on the client. By pairing WebSockets for lightweight event signaling with TanStack Query (React Query) for managed data fetching and caching, you build a resilient, event-driven frontend architecture capable of maintaining sub-100ms latency. Instead of transmitting full, deeply nested entities over open WebSocket channels, separate your concerns between Signaling and Data Transport:
  1. REST / Axios Layer: Handles authentication, complex multi-parameter queries, mutations, and complete payload transfers.
  2. WebSocket Signal Pipe: Delivers ultra-lightweight event messages (e.g., { type: "CALL_LOG_MUTATED", sessionId: "sys_9821" }).
  3. TanStack Query Invalidation: Listens to incoming signals and invalidates or updates matching query keys directly in the client cache.
Pipeline Layer
Protocol / Tool
Engineering Responsibility
Payload Overhead
Event SignalWebSocket (WSS)Pushes real-time event notifications to clients instantlyUltra-lightweight JSON (~50-100 bytes)
Data TransportREST API + AxiosFetches structured entity views on demand or cache invalidationFull JSON schema payloads
State ManagementTanStack QueryManages stale-while-revalidate caching, retries, and deduplicationIn-memory query cache
UI RenderingOnce UI ComponentsDeclaratively renders synced state changes across client dashboardsZero re-render overhead
Here is a resilient React custom hook that maintains a persistent WebSocket connection, handles heartbeat ping/pongs, and bridges incoming socket events directly into TanStack Query's QueryClient:
src/hooks/useRealtimeCacheSync.ts
import { useEffect, useRef } from "react";
import { useQueryClient } from "@tanstack/react-query";

interface SocketPayload {
type: "NOTIFICATION_RECEIVED" | "SESSION_UPDATED" | "CALL_LOG_MUTATED";
entityId?: string;
data?: Record<string, unknown>;
}

export function useRealtimeCacheSync(wsUrl: string) {
const queryClient = useQueryClient();
const socketRef = useRef<WebSocket | null>(null);

useEffect(() => {
  // 1. Establish persistent socket channel
  const ws = new WebSocket(wsUrl);
  socketRef.current = ws;

  ws.onopen = () => {
    console.log("[WebSocket Pipeline] Channel connected successfully");
  };

  ws.onmessage = (event: MessageEvent) => {
    try {
      const payload: SocketPayload = JSON.parse(event.data);

      // 2. Dispatch targeted invalidations or direct cache mutations
      switch (payload.type) {
        case "NOTIFICATION_RECEIVED":
          queryClient.invalidateQueries({ queryKey: ["notifications"] });
          break;

        case "SESSION_UPDATED":
          if (payload.entityId) {
            queryClient.invalidateQueries({ 
              queryKey: ["sessions", payload.entityId] 
            });
          }
          break;

        case "CALL_LOG_MUTATED":
          // Direct query cache update for zero-latency UI response
          if (payload.entityId && payload.data) {
            queryClient.setQueryData(
              ["call-logs", payload.entityId],
              (oldData: any) => ({ ...oldData, ...payload.data })
            );
          }
          break;

        default:
          console.warn("[WebSocket Pipeline] Unhandled event type:", payload.type);
      }
    } catch (error) {
      console.error("[WebSocket Pipeline] Error parsing incoming frame:", error);
    }
  };

  ws.onerror = (error) => {
    console.error("[WebSocket Pipeline] Socket error observed:", error);
  };

  // 3. Clean up connection on component unmount
  return () => {
    if (ws.readyState === WebSocket.OPEN) {
      ws.close();
    }
  };
}, [wsUrl, queryClient]);
}
By wiring the socket hook inside a feature component, TanStack Query automatically refetches fresh data over REST whenever an invalidation signal arrives, triggering smooth, reactive UI updates:
src/components/notifications/NotificationList.tsx
"use client";

import { useQuery } from "@tanstack/react-query";
import axios from "axios";
import { useRealtimeCacheSync } from "@/hooks/useRealtimeCacheSync";
import { Column, Row, Text, Badge } from "@/components/once-ui";

interface NotificationItem {
id: string;
message: string;
status: "unread" | "read";
timestamp: string;
}

const fetchNotifications = async (): Promise<NotificationItem[]> => {
const { data } = await axios.get("/api/v1/notifications");
return data;
};

export function NotificationList() {
// Synchronize incoming WebSocket events directly with query cache
useRealtimeCacheSync(process.env.NEXT_PUBLIC_WS_URL || "wss://api.vilsalconnect.com/ws");

const { data: notifications, isLoading, isError } = useQuery({
  queryKey: ["notifications"],
  queryFn: fetchNotifications,
  staleTime: 1000 * 60 * 5, // Keep cached data fresh for 5 minutes
});

if (isLoading) return <Text variant="body-default-s">Connecting to live feed...</Text>;
if (isError) return <Text variant="body-default-s" onBackground="danger-weak">Failed to load notifications.</Text>;

return (
  <Column gap="8" fillWidth>
    {notifications?.map((item) => (
      <Row 
        key={item.id} 
        padding="12" 
        border="neutral-alpha-medium" 
        radius="m" 
        horizontal="space-between"
        vertical="center"
      >
        <Text variant="body-default-s">{item.message}</Text>
        <Badge variant={item.status === "unread" ? "accent" : "neutral"}>
          {item.status}
        </Badge>
      </Row>
    ))}
  </Column>
);
}
Best Practices for Real-Time Sync
  1. Keep WebSocket payloads lean—transmit event signals and entity IDs instead of massive JSON trees.
  2. Let TanStack Query handle data caching, request deduplication, and HTTP fetching via Axios.
  3. Enforce proper socket teardown logic inside React effect cleanups to prevent memory leaks during page navigation.