Skip to content
Skills Library
Programming · Building & coding

tanstack

/tanstack

Type-safe React with TanStack Query (fetching, caching, mutations), Router (file-based routing, search params, loaders), and Start (SSR, server functions). Use for react-query, server state, typed search params, route loaders, or SSR.

Repository
skills ↗
Licence
MIT
Last repository change
24.10.2026

Assessment and security

100/ 100Class: good
Format25 / 25
Frontmatter with name and description, valid name, description up to 1,024 characters, name matching the folder.
Discoverability25 / 25
Description explains when to use the skill, has a reasonable length and uses third person.
Content35 / 35
At least 150 words and at most 500 lines, headings, step lists, examples or code.
Hygiene15 / 15
No placeholders such as TODO, no Windows paths, with a licence.
Riskno signals detected in the scan
Files in this package
20
Scripts
0
HTML comments
0
URLs in SKILL.md
8
Deprecation

No signals detected. Repository changed on 24.10.2026, without references to retired models or APIs.

Licence

MIT, open: use and modify while retaining author attribution.

What it does and when to use it

Type-safe React with TanStack Query (fetching, caching, mutations), Router (file-based routing, search params, loaders), and Start (SSR, server functions). Use for react-query, server state, typed search params, route loaders, or SSR.

Original author description

Type-safe React with TanStack Query (fetching, caching, mutations), Router (file-based routing, search params, loaders), and Start (SSR, server functions). Use for react-query, server state, typed search params, route loaders, or SSR.

How it works

  1. When to Use
  2. TanStack Query v5
  3. TanStack Router v1
  4. TanStack Start
  5. Best Practices
  6. Resources
Original SKILL.md headings · 398 lines, 1,596 words
SKILL.md preview
---
name: tanstack
description: Type-safe React with TanStack Query (fetching, caching, mutations), Router (file-based routing, search params, loaders), and Start (SSR, server functions). Use for react-query, server state, typed search params, route loaders, or SSR.
metadata:
  version: "0.4.5"
  categories: "development"
  topics: "tanstack, react, routing, data-fetching, ssr"
  upstream: "@tanstack/react-query@5.101.2, @tanstack/react-router@1.170.16, @tanstack/react-start@1.168.26, @tanstack/zod-adapter@1.167.0, @tanstack/router-plugin@1.168.18"
  openclaw:
    homepage: https://github.com/tenequm/skills/tree/main/skills/tanstack
    emoji: "⚛️"
---

# TanStack (Query + Router + Start)

Type-safe libraries for React applications. **Query** manages server state (fetching, caching, mutations). **Router** provides file-based routing with validated search params and data loaders. **Start** extends Router with SSR, server functions, and middleware for full-stack apps.

## When to Use

**Query** - data fetching, caching, mutations, optimistic updates, infinite scroll, streaming AI/SSE responses, tRPC v11 integration
**Router** - file-based routing, type-safe navigation, validated search params, route loaders, code splitting, preloading
**Start** - SSR/SSG, server functions (type-safe RPCs), middleware, API routes, deployment to Cloudflare/Vercel/Node

**Decision tree:**
- Client-only SPA with API calls -> Router + Query
- Full-stack with SSR/server functions -> Start + Query (Start includes Router)

## TanStack Query v5

### Setup

```tsx
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'

const queryClient = new QueryClient({
  defaultOptions: {
    queries: {
      staleTime: 1000 * 60 * 5, // 5 minutes
    },
  },
})

function App() {
  return (
    <QueryClientProvider client={queryClient}>
      <YourApp />
    </QueryClientProvider>
  )
}
```

### Queries

```tsx
import { useQuery, queryOptions } from '@tanstack/react-query'

// Reusable query definition (recommended pattern)
const todosQueryOptions = queryOptions({
  queryKey: ['todos'],
  queryFn: async () => {
    const res = await fetch('/api/todos')
    if (!res.ok) throw new Error('Failed to fetch')
    return res.json() as Promise<Todo[]>
  },
})

// In component - full type inference from queryOptions
function TodoList() {
  const { data, isLoading, error } = useQuery(todosQueryOptions)
  if (isLoading) return <Spinner />
  if (error) return <div>Error: {error.message}</div>
  return <ul>{data.map(t => <li key={t.id}>{t.title}</li>)}</ul>
}
```

### Mutations

```tsx
import { useMutation, useQueryClient } from '@tanstack/react-query'

function CreateTodo() {
  const queryClient = useQueryClient()
  const mutation = useMutation({
    mutationFn: (newTodo: { title: string }) =>
      fetch('/api/todos', { method: 'POST', body: JSON.stringify(newTodo) }).then(r => r.json()),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['todos'] })
    },
  })

  return (
    <button onClick={() => mutation.mutate({ title: 'New' })}>
      {mutation.isPending ? 'Creating...' : 'Create'}
    </button>
  )
}
```

### Key Patterns

**Query keys** - hierarchical arrays for cache management:
```tsx
['todos']                          // all todos
['todos', 'list', { page, sort }]  // filtered list
['todo', todoId]                   // single item
```

**Dependent queries** - chain with `enabled`:
```tsx
const { data: user } = useQuery({ queryKey: ['user', id], queryFn: () => fetchUser(id) })
const { data: projects } = useQuery({
  queryKey: ['projects', user?.id],
  queryFn: () => fetchProjects(user!.id),
  enabled: !!user?.id,
})
```

**Important defaults**: staleTime: 0, gcTime: 5min, retry: 3, refetchOnWindowFocus: true

**Suspense** - use `useSuspenseQuery` with `<Suspense>` boundaries

**Streamed queries** (experimental) - for AI chat/SSE:
```tsx
import { experimental_streamedQuery as streamedQuery } from '@tanstack/react-query'

const { data: chunks } = useQuery(queryOptions({
  queryKey: ['chat', sessionId],
  queryFn: streamedQuery({ streamFn: () => fetchChatStream(sessionId), refetchMode: 'reset' }),
}))
```

### DevTools

```bash
pnpm add @tanstack/react-query-devtools
```
```tsx
import { ReactQueryDevtools } from '@tanstack/react-query-devtools'
// Add inside QueryClientProvider
<ReactQueryDevtools initialIsOpen={false} />
```

### Query Deep Dives

- `query-guide.md` - Complete Query reference with all patterns
- `infinite-queries.md` - useInfiniteQuery, pagination, virtual scroll
- `optimistic-updates.md` - Optimistic UI, rollback, undo
- `query-performance.md` - staleTime tuning, deduplication, prefetching
- `query-invalidation.md` - Cache invalidation strategies, filters, predicates
- `query-typescript.md` - Type inference, generics, custom hooks

---

## TanStack Router v1

### Setup (Vite)

```bash
pnpm add @tanstack/react-router @tanstack/router-plugin
```

```ts
// vite.config.ts
import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'
import { tanstackRouter } from '@tanstack/router-plugin/vite'

export default defineConfig({
  plugins: [
    tanstackRouter({ autoCodeSplitting: true }),
    react(),
  ],
})
```

```tsx
// src/router.ts
import { createRouter } from '@tanstack/react-router'
import { routeTree } from './routeTree.gen'

export const router = createRouter({ routeTree, defaultPreload: 'intent' })

declare module '@tanstack/react-router' {
  interface Register { router: typeof router }
}
```

### File-Based Routing

Files in `src/routes/` auto-generate route config:

| Convention | Purpose | Example |
|---|---|---|
| `__root.tsx` | Root route (always rendered) | `src/routes/__root.tsx` |
| `index.tsx` | Index route | `src/routes/index.tsx` -> `/` |
| `$param` | Dynamic segment | `posts.$postId.tsx` -> `/posts/:id` |
| `_prefix` | Pathless layout | `_layout.tsx` wraps children |
| `(folder)` | Route group (no URL) | `(auth)/login.tsx` -> `/login` |

### Type-Safe Navigation

```tsx
<Link to="/posts/$postId" params={{ postId: '123' }}>View Post</Link>

// Active styling
<Link to="/posts" activeProps={{ className: 'font-bold' }}>Posts</Link>

// Imperative
const navigate = useNavigate({ from: '/posts' })
navigate({ to: '/posts/$postId', params: { postId: post.id } })
```

Always provide `from` on Link and hooks - narrows types and improves TS performance.

### Search Params

```tsx
import { zodValidator, fallback } from '@tanstack/zod-adapter'
import { z } from 'zod'

const searchSchema = z.object({
  page: fallback(z.number(), 1).default(1),
  sort: fallback(z.enum(['newest', 'oldest']), 'newest').default('newest'),
})

export const Route = createFileRoute('/products')({
  validateSearch: zodValidator(searchSchema),
  component: () => {
    const { page, sort } = Route.useSearch()
    // Writing
    return <Link from={Route.fullPath} search={prev => ({ ...prev, page: prev.page + 1 })}>Next</Link>
  },
})
```

Use `fallback(...).default(...)` from the Zod adapter (Zod v3); plain `.catch()` causes type loss. With **Zod v4** the adapter is no longer needed - pass the schema directly to `validateSearch`, and `.catch()` retains type inference.

### Data Loading

```tsx
export const Route = createFileRoute('/posts')({
  // loaderDeps: only extract what loader needs (not full search)
  loaderDeps: ({ search: { page } }) => ({ page }),
  loader: ({ deps: { page } }) => fetchPosts({ page }),
  pendingComponent: () => <Spinner />,
  component: () => {
    const posts = Route.useLoaderData()
    return <PostList posts={posts} />
  },
})
```

### Route Context (Dependency Injection)

```tsx
// __root.tsx
interface RouterContext { queryClient: QueryClient }
export const Route = createRootRouteWithContext<RouterContext>()({ component: Root })

// router.ts
const router = createRouter({ routeTree, context: { queryClient } })

// Child route - queryClient available in loader
export const Route = createFileRoute('/posts')({
  loader: ({ context: { queryClient } }) =>
    queryClient.ensureQueryData(postsQueryOptions()),
})
```

### Router Deep Dives

- `router-guide.md` - Complete Router reference with all patterns
- `search-params.md` - Custom serialization, Standard Schema, sharing params
- `data-loading.md` - Deferred loading, streaming SSR, shouldReload
- `routing-patterns.md` - Virtual routes, route masking, navigation blocking
- `code-splitting.md` - Automatic/manual splitting strategies
- `router-ssr.md` - SSR setup, streaming, hydration

---

## TanStack Start

Full-stack framework extending Router with SSR, server functions, middleware. Pre-1.0 (API stable, feature-complete, preparing for 1.0). React Server Components are available as an **experimental** feature - opt in with `tanstackStart({ rsc: { enabled: true } })` + `@vitejs/plugin-rsc` (requires React 19, Vite 7+). Vite is the default bundler; Rsbuild is also supported.

### Setup

```bash
npx @tanstack/cli@latest create   # or use TanStack Builder: https://tanstack.com/builder
```

```ts
// vite.config.ts
import { defineConfig } from 'vite'
import { tanstackStart } from '@tanstack/react-start/plugin/vite'
import viteReact from '@vitejs/plugin-react'

export default defineConfig({
  plugins: [
    tanstackStart(),
    viteReact(), // MUST come after tanstackStart()
  ],
})
```

### Server Functions

Type-safe RPCs. Server code extracted from client bundles at build time.

```tsx
import { createServerFn } from '@tanstack/react-start'
import { z } from 'zod'

// GET - no input
export const getUsers = createServerFn({ method: 'GET' })
  .handler(async () => db.users.findMany())

// POST - validated input
export const createUser = createServerFn({ method: 'POST' })
  .validator(z.object({ name: z.string(), email: z.string().email() }))
  .handler(async ({ data }) => db.users.create(data))

// Call from loader
export const Route = createFileRoute('/users')({
  loader: () => getUsers(),
  component: () => {
    const users = Route.useLoaderData()
    return <UserList users={users} />
  },
})
```

**Critical**: Loaders are isomorphic (run on server AND client). Never put secrets in loaders - use `createServerFn()` instead.

### Middleware

```tsx
import { createMiddleware } from '@tanstack/react-start'

const authMiddleware = createMiddleware({ type: 'function' })
  .server(async ({ next }) => {
    const user = await getCurrentUser()
    if (!user) throw redirect({ to: '/login' })
    return next({ context: { user } })
  })

const getProfile = createServerFn()
  .middleware([authMiddleware])
  .handler(async ({ context }) => context.user) // typed
```

Global middleware via `src/start.ts`:
```tsx
export const startInstance = createStart(() => ({
  requestMiddleware: [logger],    // all requests
  functionMiddleware: [auth],     // all server functions
}))
```

**CSRF**: Start auto-installs `createCsrfMiddleware()` for server functions *only when there is no `src/start.ts`*. Once you create `src/start.ts`, add it back explicitly, or non-GET server functions lose same-origin protection:
```tsx
requestMiddleware: [createCsrfMiddleware({ filter: (ctx) => ctx.handlerType === 'serverFn' }), logger]
```

### SSR Modes

| Mode | Use Case |
|------|----------|
| `true` (default) | SEO, performance |
| `false` | Browser-only features |
| `'data-only'` | Dashboards (data on server, render on client) |

SPA mode: `tanstackStart({ spa: { enabled: true } })` in vite.config.ts

### Deployment

- **Official partners**: Cloudflare Workers (`@cloudflare/vite-plugin`), Netlify (`@netlify/vite-plugin-tanstack-start`), Railway
- **Node/Vercel/Bun/Docker**: via Nitro
- **Static**: `tanstackStart({ prerender: { enabled: true, crawlLinks: true } })`

### Start Deep Dives

- `start-guide.md` - Complete Start reference with all patterns
- `server-functions.md` - Streaming, FormData, progressive enhancement
- `middleware.md` - sendContext, custom fetch, global config
- `ssr-modes.md` - Selective SSR, shellComponent, fallback rendering
- `server-routes.md` - Dynamic params, wildcards, pathless layouts

---

## Best Practices

1. **Use `queryOptions()` factory** for reusable, type-safe query definitions
2. **Structure query keys hierarchically** - `['entity', 'action', { filters }]`
3. **Set staleTime per data type** - static: `Infinity`, dynamic: `0`, moderate: `5min`
4. **Always validate search params** with Zod via `zodValidator` + `fallback().default()`
5. **Provide `from` on navigation** - narrows types, catches route mismatches
6. **Use route context for DI** - pass QueryClient, auth via `createRootRouteWithContext`
7. **Set `defaultPreload: 'intent'`** globally for perceived performance
8. **Enforce auth at the data boundary** - authorize inside the server function, server route, or API endpoint that reads/writes private data; `beforeLoad`/route guards are UX, not the security boundary. Never put secrets in isomorphic loaders - use `createServerFn()`
9. **Compose middleware hierarchically** - global -> route -> function
10. **Use `head()` on every content route** for SEO (title, description, OG tags)

## Resources

- **Query Docs**: https://tanstack.com/query/latest/docs/framework/react/overview
- **Router Docs**: https://tanstack.com/router/latest/docs/framework/react/overview
- **Start Docs**: https://tanstack.com/start/latest/docs/framework/react/overview
- **GitHub**: https://github.com/TanStack/query | https://github.com/TanStack/router
- **Discord**: https://discord.gg/tanstack
Files in this package (20)
  • CHANGELOG.md 6 KB
  • LICENSE.txt 9 KB
  • SKILL.md 13 KB
  • references/code-splitting.md 16 KB
  • references/data-loading.md 22 KB
  • references/infinite-queries.md 16 KB
  • references/middleware.md 20 KB
  • references/optimistic-updates.md 16 KB
  • references/query-guide.md 21 KB
  • references/query-invalidation.md 17 KB
  • references/query-performance.md 18 KB
  • references/query-typescript.md 19 KB
  • references/router-guide.md 15 KB
  • references/router-ssr.md 18 KB
  • references/routing-patterns.md 21 KB
  • references/search-params.md 21 KB
  • references/server-functions.md 25 KB
  • references/server-routes.md 18 KB
  • references/ssr-modes.md 33 KB
  • references/start-guide.md 15 KB

Versions

The database has no other skills named tanstack.

Database snapshot: 13.11.2026 · package version affd1693283d (SHA-256 digest of the entire package)

Downloads in the last 30 days: 0 · ranking

Report a problem with this skill: harmful content, incorrect descriptions or an author’s removal request.

Similar skills

  • 100react-tanstack-router
    Use when implementing routing in a React app (NOT Next.js) with TanStack Router — file-based routes, loaders, search params.
  • 100tanstack-router
    TanStack Router for React with file-based routing. Covers route definitions, layouts, authentication guards, loaders, and type-safe navigation. USE WHEN: user mentions "TanStack Router", "file-based routing", "type-safe routing", "route loaders", "beforeLoad", asks about…
  • 90TanStack Router
    Expert guidance for TanStack Router including file-based routing, type-safe navigation, route loaders, search params, nested routes, and lazy loading. Use this when building type-safe React applications with client-side routing.
  • 100start-routing-data
    Use when loading data in Start routes — isomorphic loaders, TanStack Query in a loader, mutations, or per-route SSR. Do NOT use for generic Router/Query API.
  • 100tanstack-start
    Build full-stack React apps with TanStack Start. Use when a user asks to create a full-stack React application with type-safe server functions, set up file-based routing with SSR/SSG/SPA modes, build APIs with middleware and validation, implement server-side data fetching with…
  • 100tanstack-router
    Type-safe routing for React with file-based routes, validated search params, loaders, and automatic code splitting. Use when someone asks to "set up routing for React", "type-safe router", "TanStack Router", "file-based routing", "search params validation", "replace React Router…

Feedback and reports

Your message goes to Bartosz Sokoliński. An email address is needed only for a reply. See the privacy policy.