Back to Skills

grey-haven-tanstack-patterns

greyhaven-ai
Updated Today
30 views
15
2
15
View on GitHub
Metareactdesigndata

About

This Claude Skill applies Grey Haven Studio's patterns for building React applications with TanStack Start. It provides file-based routing with TanStack Router, implements data fetching using TanStack Query with staleTime configuration, and utilizes Start server functions. Use this skill when developing React applications with the TanStack ecosystem to follow established best practices.

Quick Install

Claude Code

Recommended
Plugin CommandRecommended
/plugin add https://github.com/greyhaven-ai/claude-code-config
Git CloneAlternative
git clone https://github.com/greyhaven-ai/claude-code-config.git ~/.claude/skills/grey-haven-tanstack-patterns

Copy and paste this command in Claude Code to install this skill

Documentation

Grey Haven TanStack Patterns

Follow Grey Haven Studio's patterns for TanStack Start, Router, and Query in React 19 applications.

TanStack Stack Overview

Grey Haven uses the complete TanStack ecosystem:

  • TanStack Start: Full-stack React framework with server functions
  • TanStack Router: Type-safe file-based routing with loaders
  • TanStack Query: Server state management with caching
  • TanStack Table (optional): Data grids and tables
  • TanStack Form (optional): Type-safe form handling

Critical Patterns

1. File-Based Routing Structure

src/routes/
├── __root.tsx              # Root layout (wraps all routes)
├── index.tsx               # Homepage (/)
├── _authenticated/         # Protected routes group (underscore prefix)
│   ├── _layout.tsx        # Auth layout wrapper
│   ├── dashboard.tsx      # /dashboard
│   └── settings/
│       └── index.tsx      # /settings
└── users/
    ├── index.tsx          # /users
    └── $userId.tsx        # /users/:userId (dynamic param)

Key conventions:

  • __root.tsx - Root layout with QueryClient provider
  • _authenticated/ - Protected route groups (underscore prefix)
  • _layout.tsx - Layout wrapper for route groups
  • $param.tsx - Dynamic route parameters

2. TanStack Query Defaults

const queryClient = new QueryClient({
  defaultOptions: {
    queries: {
      staleTime: 60000, // 1 minute default
      retry: 1,
      refetchOnWindowFocus: false,
    },
  },
});

3. Query Key Patterns

// ✅ CORRECT - Specific to general
queryKey: ["user", userId]
queryKey: ["users", { tenantId, page: 1 }]
queryKey: ["organizations", orgId, "teams"]

// ❌ WRONG
queryKey: [userId]                    // Missing resource type
queryKey: ["getUser", userId]        // Don't include function name
queryKey: [{ id: userId }]           // Object first is confusing

4. Server Functions with Multi-Tenant

// ALWAYS include tenant_id parameter
export const getUserById = createServerFn("GET", async (
  userId: string,
  tenantId: string
) => {
  const user = await db.query.users.findFirst({
    where: and(
      eq(users.id, userId),
      eq(users.tenant_id, tenantId) // Multi-tenant isolation!
    ),
  });

  if (!user) throw new Error("User not found");
  return user;
});

5. Route Loaders

export const Route = createFileRoute("/_authenticated/dashboard")({
  // Loader fetches data on server before rendering
  loader: async ({ context }) => {
    const tenantId = context.session.tenantId;
    return await getDashboardData(tenantId);
  },
  component: DashboardPage,
});

function DashboardPage() {
  const data = Route.useLoaderData(); // Type-safe loader data
  return <div>...</div>;
}

6. Mutations with Cache Invalidation

const mutation = useMutation({
  mutationFn: (data: UserUpdate) => updateUser(userId, data),
  // Always invalidate queries after mutation
  onSuccess: () => {
    queryClient.invalidateQueries({ queryKey: ["user", userId] });
  },
});

Caching Strategy

Grey Haven uses these staleTime defaults:

Data TypestaleTimeUse Case
Auth data5 minutesUser sessions, tokens
User profiles1 minuteUser details
Lists1 minuteData tables, lists
Static/config10 minutesSettings, configs
Realtime0 (always refetch)Notifications
const STALE_TIMES = {
  auth: 5 * 60 * 1000,        // 5 minutes
  user: 1 * 60 * 1000,        // 1 minute
  list: 1 * 60 * 1000,        // 1 minute
  static: 10 * 60 * 1000,     // 10 minutes
  realtime: 0,                // Always refetch
};

Supporting Documentation

All supporting files are under 500 lines per Anthropic best practices:

When to Apply This Skill

Use this skill when:

  • Building TanStack Start applications
  • Implementing routing with TanStack Router
  • Managing server state with TanStack Query
  • Creating server functions for data fetching
  • Optimizing query performance with caching
  • Implementing multi-tenant data access
  • Setting up authentication flows with route protection
  • Building data-heavy React applications

Template Reference

These patterns are from Grey Haven's production template:

  • cvi-template: TanStack Start + Router + Query + React 19

Critical Reminders

  1. staleTime: Default 60000ms (1 minute) for queries
  2. Query keys: Specific to general (["user", userId], not [userId])
  3. Server functions: Always include tenant_id parameter
  4. Multi-tenant: Filter by tenant_id in all server functions
  5. Loaders: Use for server-side data fetching before render
  6. Mutations: Invalidate queries after successful mutation
  7. Prefetching: Use for performance on hover/navigation
  8. Error handling: Always handle error state in queries
  9. RLS: Server functions use RLS-enabled database connection
  10. File-based routing: Underscore prefix (_) for route groups/layouts

GitHub Repository

greyhaven-ai/claude-code-config
Path: grey-haven-plugins/research/skills/tanstack-patterns

Related Skills

content-collections

Meta

This skill provides a production-tested setup for Content Collections, a TypeScript-first tool that transforms Markdown/MDX files into type-safe data collections with Zod validation. Use it when building blogs, documentation sites, or content-heavy Vite + React applications to ensure type safety and automatic content validation. It covers everything from Vite plugin configuration and MDX compilation to deployment optimization and schema validation.

View skill

langchain

Meta

LangChain is a framework for building LLM applications using agents, chains, and RAG pipelines. It supports multiple LLM providers, offers 500+ integrations, and includes features like tool calling and memory management. Use it for rapid prototyping and deploying production systems like chatbots, autonomous agents, and question-answering services.

View skill

Algorithmic Art Generation

Meta

This skill helps developers create algorithmic art using p5.js, focusing on generative art, computational aesthetics, and interactive visualizations. It automatically activates for topics like "generative art" or "p5.js visualization" and guides you through creating unique algorithms with features like seeded randomness, flow fields, and particle systems. Use it when you need to build reproducible, code-driven artistic patterns.

View skill

webapp-testing

Testing

This Claude Skill provides a Playwright-based toolkit for testing local web applications through Python scripts. It enables frontend verification, UI debugging, screenshot capture, and log viewing while managing server lifecycles. Use it for browser automation tasks but run scripts directly rather than reading their source code to avoid context pollution.

View skill