惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
P
Palo Alto Networks Blog
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
P
Privacy & Cybersecurity Law Blog
Security Archives - TechRepublic
Security Archives - TechRepublic
阮一峰的网络日志
阮一峰的网络日志
Recent Announcements
Recent Announcements
P
Proofpoint News Feed
H
Hacker News: Front Page
H
Help Net Security
云风的 BLOG
云风的 BLOG
H
Heimdal Security Blog
C
CXSECURITY Database RSS Feed - CXSecurity.com
L
Lohrmann on Cybersecurity
C
Check Point Blog
Google DeepMind News
Google DeepMind News
Forbes - Security
Forbes - Security
P
Proofpoint News Feed
Google DeepMind News
Google DeepMind News
I
InfoQ
The GitHub Blog
The GitHub Blog
The Cloudflare Blog
I
Intezer
L
LINUX DO - 最新话题
K
Kaspersky official blog
Attack and Defense Labs
Attack and Defense Labs
C
CERT Recently Published Vulnerability Notes
aimingoo的专栏
aimingoo的专栏
S
SegmentFault 最新的问题
NISL@THU
NISL@THU
人人都是产品经理
人人都是产品经理
雷峰网
雷峰网
cs.CV updates on arXiv.org
cs.CV updates on arXiv.org
Vercel News
Vercel News
C
Cyber Attacks, Cyber Crime and Cyber Security
T
Threatpost
Y
Y Combinator Blog
S
Security Affairs
Latest news
Latest news
T
Threat Research - Cisco Blogs
T
Tailwind CSS Blog
C
Cisco Blogs
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
P
Privacy International News Feed
Jina AI
Jina AI
Apple Machine Learning Research
Apple Machine Learning Research
Cisco Talos Blog
Cisco Talos Blog
T
Troy Hunt's Blog
S
Securelist
MongoDB | Blog
MongoDB | Blog

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
Real-Time Dashboard in Next.js with TanStack Query + Zustand
Iurii Rogulia · 2026-06-15 · via DEV Community

An admin dashboard sounds like a simple project. List some data, add some filters, show some charts. In practice, it's where all the product complexity concentrates: real-time data that needs to stay fresh, filter state that needs to survive navigation, error boundaries that need to tell you about production failures before users report them, and data visualization that shouldn't add 300 kB to your bundle for a single chart.

I've built admin dashboards for vatnode.dev and HTPBE?. The HTPBE? dashboard is server-rendered with no client-side data fetching — appropriate for a low-traffic internal tool where real-time isn't needed. The vatnode dashboard needed live API usage metrics, error rates, and user activity that update while you're looking at them.

This article covers the client-side architecture: TanStack Query for data fetching and polling, Zustand for dashboard filter state, and Sentry for error monitoring.

The Architecture Question: Server Components vs Client

Next.js App Router gives you a real choice here. React Server Components fetch data directly — no client-side JavaScript, no loading states, no stale data problem. I used this approach for the HTPBE? admin dashboard and it works very well for a static view of current state.

But for real-time metrics, Server Components aren't the right tool. You want data to update on the screen without a full page reload. That means client-side data fetching, which means TanStack Query. The broader SaaS production checklist covers where admin dashboards fit in the full architecture.

The architecture I use: Server Components for the initial page shell (authentication, static configuration, first data fetch), Client Components for the interactive dashboard panels that need to stay live. This keeps the Time to First Byte fast — the page renders with real data immediately — and adds live updates on top without requiring a WebSocket.

// app/(dashboard)/dashboard/page.tsx — Server Component
import { auth } from "@/lib/auth";
import { redirect } from "next/navigation";
import { DashboardClient } from "./dashboard-client";
import { getInitialStats } from "@/lib/stats";

export default async function DashboardPage() {
  const session = await auth();
  if (!session) redirect("/login");

  // Initial data fetch on the server — no loading spinner on first load
  const initialStats = await getInitialStats(session.user.id);

  return <DashboardClient initialStats={initialStats} userId={session.user.id} />;
}

The initialStats becomes the initialData in TanStack Query, which means the dashboard renders immediately with real data. TanStack Query then takes over for polling, so the data stays fresh without another full page render.

TanStack Query: Polling vs WebSockets

slug="mvp-development"
text="Building a SaaS that needs a production-grade admin dashboard with live metrics, error monitoring, and filter state that survives navigation? I own the full stack."
/>

The question that comes up immediately: why polling and not WebSockets? WebSockets give you true real-time push — the server notifies the client the instant data changes. Polling checks for changes on a schedule.

My answer: for an admin dashboard, polling is almost always sufficient and significantly simpler to operate. The questions an admin dashboard answers — "what are my API error rates?" "how many users are active today?" — don't require millisecond latency. A 30-second polling interval is fine. WebSockets require a persistent server connection, connection management, reconnection logic, and a different deployment model (can't use serverless for WebSocket handlers on Vercel without additional infrastructure).

Here's the TanStack Query setup for API usage metrics:

// app/(dashboard)/dashboard/dashboard-client.tsx
"use client";

import { useQuery, QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { useDashboardStore } from "@/store/dashboard";

const queryClient = new QueryClient({
  defaultOptions: {
    queries: {
      staleTime: 30_000,    // Consider data stale after 30 seconds
      gcTime: 5 * 60_000,   // Keep unused data in cache for 5 minutes
      retry: 2,
      retryDelay: (attemptIndex) => Math.min(1000 * 2 ** attemptIndex, 10_000),
    },
  },
});

export function DashboardClient({
  initialStats,
  userId,
}: {
  initialStats: UsageStats;
  userId: string;
}) {
  return (
    <QueryClientProvider client={queryClient}>
      <DashboardContent initialStats={initialStats} userId={userId} />
    </QueryClientProvider>
  );
}

function DashboardContent({
  initialStats,
  userId,
}: {
  initialStats: UsageStats;
  userId: string;
}) {
  // Read filter state from Zustand
  const { timeRange, environment } = useDashboardStore();

  const { data: stats, isLoading, error, dataUpdatedAt } = useQuery({
    queryKey: ["usage-stats", userId, timeRange, environment],
    queryFn: () => fetchUsageStats({ userId, timeRange, environment }),
    initialData: initialStats,
    refetchInterval: 30_000, // Poll every 30 seconds
    refetchIntervalInBackground: false, // Stop polling when tab is not focused
  });

  if (isLoading && !stats) return <DashboardSkeleton />;
  if (error) return <DashboardError error={error} />;

  return (
    <div>
      <StatsGrid stats={stats} />
      <ActivityChart userId={userId} timeRange={timeRange} />
      <LastUpdated timestamp={dataUpdatedAt} />
    </div>
  );
}

refetchIntervalInBackground: false is the flag I always set for admin dashboards. If you leave it true, every browser tab running the dashboard makes API calls every 30 seconds even when the tab is in the background. On a shared staging environment with 3 developers, that's 3× the load. Small detail, real impact.

The queryKey array includes the filter state — timeRange and environment. When a filter changes, TanStack Query fetches fresh data for the new combination and caches the old data separately. Switch back to the previous filter and it renders from cache immediately, re-validating in the background.

Zustand for Dashboard State

The dashboard has filter state that needs to:

  • Persist across panel switches (navigate to Users, come back to Overview — filters should be the same)
  • Be accessible from multiple components without prop drilling
  • Not cause unnecessary re-renders in components that don't use it

This is exactly what Zustand is for.

// store/dashboard.ts
import { create } from "zustand";
import { persist } from "zustand/middleware";

type TimeRange = "1h" | "24h" | "7d" | "30d";
type Environment = "live" | "test" | "all";

interface DashboardState {
  timeRange: TimeRange;
  environment: Environment;
  selectedUserId: string | null;

  setTimeRange: (range: TimeRange) => void;
  setEnvironment: (env: Environment) => void;
  setSelectedUser: (userId: string | null) => void;
  reset: () => void;
}

const initialState = {
  timeRange: "24h" as TimeRange,
  environment: "live" as Environment,
  selectedUserId: null,
};

export const useDashboardStore = create<DashboardState>()(
  persist(
    (set) => ({
      ...initialState,
      setTimeRange: (timeRange) => set({ timeRange }),
      setEnvironment: (environment) => set({ environment }),
      setSelectedUser: (selectedUserId) => set({ selectedUserId }),
      reset: () => set(initialState),
    }),
    {
      name: "dashboard-filters",
      partialize: (state) =>
        // Only persist the filter values, not the setter functions
        ({
          timeRange: state.timeRange,
          environment: state.environment,
          // Don't persist selectedUserId — clear on reload
        }),
    }
  )
);

The persist middleware with partialize is the important piece. Without partialize, Zustand would try to serialize the setter functions to localStorage — which fails silently. partialize lets you specify exactly which state slices to persist.

The time range and environment preferences persist across reloads (sensible UX — why should the user have to re-select "7d" every time they open the dashboard?). The selected user ID doesn't persist — on reload, you want to see the full list, not land on a specific user's detail view.

Filter Components Wired to Zustand

// components/dashboard/TimeRangeSelector.tsx
"use client";

import { useDashboardStore } from "@/store/dashboard";

const TIME_RANGES = [
  { value: "1h" as const, label: "1 hour" },
  { value: "24h" as const, label: "24 hours" },
  { value: "7d" as const, label: "7 days" },
  { value: "30d" as const, label: "30 days" },
];

export function TimeRangeSelector() {
  const { timeRange, setTimeRange } = useDashboardStore();

  return (
    <div className="flex gap-1 rounded-lg border p-1">
      {TIME_RANGES.map(({ value, label }) => (
        <button
          key={value}
          onClick={() => setTimeRange(value)}
          className={`rounded px-3 py-1 text-sm transition-colors ${
            timeRange === value
              ? "bg-primary text-primary-foreground"
              : "hover:bg-muted"
          }`}
        >
          {label}
        </button>
      ))}
    </div>
  );
}

When setTimeRange is called, Zustand updates the store, which triggers a re-render only in components that subscribed to timeRange. The useQuery hook in DashboardContent has timeRange in its queryKey, so it automatically fires a new request.

Activity Chart Without a Chart Library

For the daily API call activity chart, I made the same decision as in the HTPBE? dashboard: no chart library. A simple bar chart does not justify adding Recharts (~400 kB), Chart.js (~300 kB), or even Nivo (~1 MB) to the bundle.

The technique: CSS proportional heights, pure JSX:

// components/dashboard/ActivityChart.tsx
"use client";

import { useQuery } from "@tanstack/react-query";
import { useDashboardStore } from "@/store/dashboard";

interface DayActivity {
  date: string;  // "2026-04-01"
  count: number;
}

export function ActivityChart({ userId }: { userId: string }) {
  const { timeRange, environment } = useDashboardStore();

  const { data: activityData } = useQuery<DayActivity[]>({
    queryKey: ["activity-chart", userId, timeRange, environment],
    queryFn: () => fetchActivityData({ userId, timeRange, environment }),
    refetchInterval: 60_000, // Chart updates less frequently than KPIs
  });

  if (!activityData || activityData.length === 0) {
    return <div className="h-32 animate-pulse rounded bg-muted" />;
  }

  const maxCount = Math.max(...activityData.map((d) => d.count), 1);

  return (
    <div>
      <h3 className="mb-3 text-sm font-medium text-muted-foreground">
        API Calls
      </h3>
      <div className="flex h-32 items-end gap-0.5">
        {activityData.map((day, i) => {
          const pct = (day.count / maxCount) * 100;
          const minHeight = day.count > 0 ? 3 : 0; // Ensure non-zero days are visible

          return (
            <div
              key={i}
              className="group relative flex flex-1 flex-col items-center justify-end"
            >
              <div
                className="w-full rounded-t bg-primary/60 transition-all group-hover:bg-primary"
                style={{ height: `${Math.max(pct, minHeight)}%` }}
              />
              {/* Tooltip on hover */}
              <div className="pointer-events-none absolute bottom-full mb-1 hidden whitespace-nowrap rounded bg-popover px-2 py-1 text-xs shadow group-hover:block">
                {formatDate(day.date)}: {day.count.toLocaleString()} calls
              </div>
            </div>
          );
        })}
      </div>
      {/* X-axis: first and last date labels */}
      <div className="mt-1 flex justify-between text-xs text-muted-foreground">
        <span>{formatDateShort(activityData[0]?.date)}</span>
        <span>{formatDateShort(activityData[activityData.length - 1]?.date)}</span>
      </div>
    </div>
  );
}

function formatDate(dateStr: string): string {
  return new Date(dateStr).toLocaleDateString("en-GB", {
    day: "2-digit",
    month: "short",
  });
}

function formatDateShort(dateStr: string | undefined): string {
  if (!dateStr) return "";
  return new Date(dateStr).toLocaleDateString("en-GB", {
    day: "2-digit",
    month: "short",
  });
}

40 lines, 0 dependencies, works correctly. The Math.max(pct, minHeight) ensures a day with one API call still shows a visible bar even when the month's maximum is 10,000 calls.

If you need interactivity beyond hover tooltips — zoom, brush selection, multiple data series with axes — then a chart library is justified. For a "how many API calls per day" bar chart, it isn't.

Sentry for Error Monitoring

Sentry is the error monitoring layer — it captures unhandled exceptions, records context (user ID, component tree, recent actions), and sends alerts.

// instrumentation.ts (Next.js instrumentation hook)
export async function register() {
  if (process.env.NEXT_RUNTIME === "nodejs") {
    const Sentry = await import("@sentry/nextjs");
    Sentry.init({
      dsn: process.env.SENTRY_DSN,
      environment: process.env.NODE_ENV,
      tracesSampleRate: 0.1, // Sample 10% of transactions for performance monitoring
      // Don't send errors from localhost
      enabled: process.env.NODE_ENV === "production",
    });
  }
}

For the dashboard specifically, I add Sentry error boundaries around the data panels so a failure in one panel doesn't crash the entire dashboard:

// components/dashboard/ErrorBoundary.tsx
"use client";

import * as Sentry from "@sentry/nextjs";
import { ErrorBoundary } from "@sentry/nextjs";
import type { ReactNode } from "react";

interface DashboardErrorBoundaryProps {
  panelName: string;
  children: ReactNode;
}

export function DashboardErrorBoundary({
  panelName,
  children,
}: DashboardErrorBoundaryProps) {
  return (
    <ErrorBoundary
      fallback={({ error, resetError }) => (
        <div className="rounded-lg border border-destructive/30 bg-destructive/10 p-4">
          <p className="text-sm text-destructive">
            Failed to load {panelName}.{" "}
            <button
              onClick={resetError}
              className="underline hover:no-underline"
            >
              Retry
            </button>
          </p>
          {process.env.NODE_ENV === "development" && (
            <pre className="mt-2 text-xs text-muted-foreground">
              {error instanceof Error ? error.message : String(error)}
            </pre>
          )}
        </div>
      )}
      onError={(error, componentStack) => {
        // Tag the error with the panel name for filtering in Sentry
        Sentry.withScope((scope) => {
          scope.setTag("dashboard_panel", panelName);
          scope.setExtra("componentStack", componentStack);
          Sentry.captureException(error);
        });
      }}
    >
      {children}
    </ErrorBoundary>
  );
}

Usage in the dashboard layout:


  <UsageStatsPanel userId={userId} />

  <ActivityChart userId={userId} />

  <RecentChecksTable userId={userId} />

When one panel fails — say, the activity chart query throws a network error — the other panels continue working and the user sees a "Failed to load Activity Chart" message with a retry button. Sentry captures the error tagged with dashboard_panel: "Activity Chart" so I can filter for it specifically.

TanStack Query + Sentry Integration

One useful combination: capture query errors to Sentry automatically via a global error callback:

// lib/query-client.ts
import { QueryClient } from "@tanstack/react-query";
import * as Sentry from "@sentry/nextjs";

export const queryClient = new QueryClient({
  defaultOptions: {
    queries: {
      staleTime: 30_000,
      retry: 2,
    },
    mutations: {
      onError: (error) => {
        Sentry.captureException(error, {
          tags: { source: "tanstack-mutation" },
        });
      },
    },
  },
  // TanStack Query v5: global error handling
  mutationCache: undefined, // configured via QueryCache below
});

// Capture query errors globally
queryClient.getQueryCache().config = {
  onError: (error, query) => {
    // Only capture after all retries are exhausted
    if (query.state.fetchFailureCount === 2) {
      Sentry.captureException(error, {
        tags: {
          source: "tanstack-query",
          queryKey: JSON.stringify(query.queryKey),
        },
      });
    }
  },
};

This means I don't have to add .catch((err) => Sentry.captureException(err)) to every useQuery call — errors bubble up automatically.

Production Considerations

Don't poll when the tab is not focused. refetchIntervalInBackground: false is the flag. On a shared dashboard with multiple admins, every open tab polls independently. 5 admins × 30-second polling × 10 queries = 10 requests per second. Not catastrophic, but unnecessary.

Invalidate cache on user actions. If an admin triggers an action (revoke an API key, update a user's plan), invalidate the relevant query so the dashboard reflects the change immediately:

// After revoking an API key
await revokeApiKey(keyId);
queryClient.invalidateQueries({ queryKey: ["user-api-keys", userId] });
queryClient.invalidateQueries({ queryKey: ["usage-stats", userId] });

Use select to transform data in the query. If your API returns raw database rows and you need a derived format for the chart, transform in the select option — it runs on cached data without triggering a refetch:

useQuery({
  queryKey: ["activity", userId],
  queryFn: fetchActivity,
  select: (data) => ({
    chartData: data.map((d) => ({ date: d.day, count: d.total })),
    totalCalls: data.reduce((sum, d) => sum + d.total, 0),
  }),
});


If you're building an admin dashboard or internal tool that needs real-time metrics and needs to be solid when things go wrong — get in touch. For SaaS MVP development where the admin dashboard is one piece of a larger product, I own the full stack from schema to deployment. I'm available for freelance projects and long-term engagements.


Related projects: HTPBE? Admin Dashboard — the server-rendered version of this problem. vatnode.dev — the SaaS that needed the client-side polling version.

Further reading: