Skip to main content
skill CX Codex

code-splitting — Claude Code skill: lazy-load route components with TanStack Router

code-splitting — a skill for TanStack Router that splits route code into critical (config, loaders) and lazy (components). Automatically generates separate chunks per route, or manually control splitting with .lazy.tsx files.

MIT 212 installs ★ 15,341 updated 2026-10-25

Install into Claude Code · Skills CLI (Vercel) All methods and platforms ↓
npx skills add TanStack/router --skill code-splitting -a claude-code
Open on GitHub

What code-splitting does

TanStack Router distinguishes critical route code—path parsing, validateSearch, loader, context—from lazy code: components and error/pending handlers. This skill enables automatic splitting (autoCodeSplitting: true) in the Vite plugin, so you write everything in one routes/posts.tsx file and components automatically land in their own chunk.

For CLI tools without a bundler plugin, split manually: critical parts in routes/posts.tsx, lazy parts in routes/posts.lazy.tsx using createLazyFileRoute. In separate files, use getRouteApi('/posts') to access typed hooks like useLoaderData, useParams, useSearch without importing the Route object itself—importing Route defeats splitting. Per-route overrides via codeSplitGroupings let you bundle a loader and component together if separate fetches cost extra async overhead. Global defaultBehavior and splitBehavior in vite.config.ts fine-tune grouping across route patterns. CRITICAL: exported component functions end up in the main bundle; keep them as plain functions inside the route file or move them to .lazy.tsx with createLazyFileRoute.

What it helps with

  • Split route components into separate chunks without code duplication
  • Keep loaders in the main bundle so routes load in parallel with components
  • Get typed hooks in a .lazy.tsx file without breaking code splitting
  • Override split logic for a single route or group of routes
  • Configure automatic splitting in Vite or set up manual splitting for other bundlers

Example prompts for the agent

  • Enable automatic code-splitting in vite.config.ts by setting autoCodeSplitting: true in the tanstackRouter plugin
  • Call getRouteApi('/posts') in a component inside posts.lazy.tsx to get typed access to useLoaderData and useParams
  • Bundle a loader with its component using codeSplitGroupings: [['loader', 'component']] in a route with heavy data logic

How to install code-splitting

1Skills CLI (Vercel)

npx skills add TanStack/router --skill code-splitting -a claude-code

2Manually: put the files in place

~/.claude/skills/code-splitting/SKILL.md

Copy the whole skill folder; for one project use .claude/skills/code-splitting/

Step by step, with commands for each platform: How to install skills in Claude Code: five ways

Questions about code-splitting

How do I install code-splitting for Claude Code?

Run npx skills add TanStack/router --skill code-splitting -a claude-code, then check ~/.claude/skills/code-splitting/SKILL.md for project-specific setup.

What does code-splitting do?

It splits route code into critical parts (config, loader) that stay in the main bundle and lazy parts (components) that load separately. This shrinks the initial bundle and speeds up first paint.

Why does my component stay in the main bundle if I export it?

Exported component functions are not split—they automatically become part of the main bundle. Keep components as plain functions in the route file or use createLazyFileRoute in a separate .lazy.tsx file instead.

Source text

SKILL.md · MIT
---
name: code-splitting
description: >-
  Automatic code splitting (autoCodeSplitting), .lazy.tsx convention,
  createLazyFileRoute, createLazyRoute, lazyRouteComponent, getRouteApi
  for typed hooks in split files, codeSplitGroupings per-route override,
  splitBehavior programmatic config, critical vs non-critical properties.
metadata:
  type: sub-skill
  library: tanstack-router
  library_version: '1.171.15'
requires:
  - router-core
sources:
  - TanStack/router:docs/router/guide/code-splitting.md
  - TanStack/router:docs/router/guide/automatic-code-splitting.md
---

# Code Splitting

TanStack Router separates route code into **critical** (required to match and start loading) and **non-critical** (can be lazy-loaded). The bundler plugin can split automatically, or you can split manually with `.lazy.tsx` files.

> **CRITICAL**: Never `export` component functions from route files — exported functions are included in the main bundle and bypass code splitting entirely.

> **CRITICAL**: Use `getRouteApi('/path')` in code-split files, NOT `import { Route } from './route'`. Importing Route defeats code splitting.

## What Stays in the Main Bundle (Critical)

- Path parsing/serialization
- `validateSearch`
- `loader`, `beforeLoad`
- Route context, static data
- Links, scripts, styles

## What Gets Split (Non-Critical)

- `component`
- `errorComponent`
- `pendingComponent`
- `notFoundComponent`

> The `loader` is NOT split by default. It is already async, so splitting it adds a double async cost: fetch the chunk, then execute the loader. Only split the loader if you have a specific reason.

## Setup: Automatic Code Splitting

Enable `autoCodeSplitting: true` in the bundler plugin. This is the recommended approach.

```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: [
    // TanStack Router plugin MUST come before the framework plugin
    tanstackRouter({
      autoCodeSplitting: true,
    }),
    react(),
  ],
})
```

With this enabled, route files are automatically transformed. Components are split into separate chunks; loaders stay in the main bundle. No `.lazy.tsx` files needed.

```tsx
// src/routes/posts.tsx — everything in one file, splitting is automatic
import { createFileRoute } from '@tanstack/react-router'
import { fetchPosts } from '../api'

export const Route = createFileRoute('/posts')({
  loader: fetchPosts,
  component: PostsComponent,
})

// NOT exported — this is critical for automatic code splitting to work
function PostsComponent() {
  const posts = Route.useLoaderData()
  return (
    <ul>
      {posts.map((post) => (
        <li key={post.id}>{post.title}</li>
      ))}
    </ul>
  )
}
```

## Manual Splitting with `.lazy.tsx`

If you cannot use automatic code splitting (e.g. CLI-only, no bundler plugin), split manually into two files:

```tsx
// src/routes/posts.tsx — critical route config only
import { createFileRoute } from '@tanstack/react-router'
import { fetchPosts } from '../api'

export const Route = createFileRoute('/posts')({
  loader: fetchPosts,
})
```

```tsx
// src/routes/posts.lazy.tsx — non-critical (lazy-loaded)
import { createLazyFileRoute } from '@tanstack/react-router'

export const Route = createLazyFileRoute('/posts')({
  component: PostsComponent,
})

function PostsComponent() {
  // Use getRouteApi to access typed hooks without importing Route
  return <div>Posts</div>
}
```

`createLazyFileRoute` supports only: `component`, `errorComponent`, `pendingComponent`, `notFoundComponent`.

## Virtual Routes

If splitting leaves the critical route file empty, delete it entirely. A virtual route is auto-generated in `routeTree.gen.ts`:

```tsx
// src/routes/about.lazy.tsx — no about.tsx needed
import { createLazyFileRoute } from '@tanstack/react-router'

export const Route = createLazyFileRoute('/about')({
  component: () => <h1>About Us</h1>,
})
```

## Code-Based Splitting

For code-based (non-file-based) routing, use `createLazyRoute` and the `.lazy()` method:

```tsx
// src/posts.lazy.tsx
import { createLazyRoute } from '@tanstack/react-router'

export const Route = createLazyRoute('/posts')({
  component: PostsComponent,
})

function PostsComponent() {
  return <div>Posts</div>
}
```

```tsx
// src/app.tsx
import { createRoute } from '@tanstack/react-router'

const postsRoute = createRoute({
  getParentRoute: () => rootRoute,
  path: '/posts',
}).lazy(() => import('./posts.lazy').then((d) => d.Route))
```

## Accessing Typed Hooks in Split Files: `getRouteApi`

When your component lives in a separate file, use `getRouteApi` to get typed access to route hooks without importing the Route object:

```tsx
// src/routes/posts.lazy.tsx
import { createLazyFileRoute, getRouteApi } from '@tanstack/react-router'

const routeApi = getRouteApi('/posts')

export const Route = createLazyFileRoute('/posts')({
  component: PostsComponent,
})

function PostsComponent() {
  const posts = routeApi.useLoaderData()
  const { page } = routeApi.useSearch()
  const params = routeApi.useParams()
  const context = routeApi.useRouteContext()
  return <div>Posts page {page}</div>
}
```

`getRouteApi` provides: `useLoaderData`, `useLoaderDeps`, `useMatch`, `useParams`, `useRouteContext`, `useSearch`.

## Per-Route Split Overrides: `codeSplitGroupings`

Override split behavior for a specific route by adding `codeSplitGroupings` directly in the route file:

```tsx
// src/routes/posts.tsx
import { createFileRoute } from '@tanstack/react-router'
import { loadPostsData } from './-heavy-posts-utils'

export const Route = createFileRoute('/posts')({
  // Bundle loader and component together for this route
  codeSplitGroupings: [['loader', 'component']],
  loader: () => loadPostsData(),
  component: PostsComponent,
})

function PostsComponent() {
  const data = Route.useLoaderData()
  return <div>{data.title}</div>
}
```

## Global Split Configuration

### `defaultBehavior` — Change Default Groupings

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

export default defineConfig({
  plugins: [
    tanstackRouter({
      autoCodeSplitting: true,
      codeSplittingOptions: {
        defaultBehavior: [
          // Bundle all UI components into one chunk
          [
            'component',
            'pendingComponent',
            'errorComponent',
            'notFoundComponent',
          ],
        ],
      },
    }),
  ],
})
```

### `splitBehavior` — Programmatic Per-Route Logic

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

export default defineConfig({
  plugins: [
    tanstackRouter({
      autoCodeSplitting: true,
      codeSplittingOptions: {
        splitBehavior: ({ routeId }) => {
          if (routeId.startsWith('/posts')) {
            return [['loader', 'component']]
          }
          // All other routes use defaultBehavior
        },
      },
    }),
  ],
})
```

### Precedence Order

1. Per-route `codeSplitGroupings` (highest)
2. `splitBehavior` function
3. `defaultBehavior` option (lowest)

## Common Mistakes

### 1. HIGH: Exporting component functions prevents code splitting

```tsx
// WRONG — export puts PostsComponent in the main bundle
export function PostsComponent() {
  return <div>Posts</div>
}

// CORRECT — no export, function stays in the split chunk
function PostsComponent() {
  return <div>Posts</div>
}
```

### 2. MEDIUM: Trying to code-split the root route

`__root.tsx` does not support code splitting. It is always rendered regardless of the current route. Do not create `__root.lazy.tsx`.

### 3. MEDIUM: Splitting the loader adds double async cost

```tsx
// AVOID unless you have a specific reason
codeSplittingOptions: {
  defaultBehavior: [
    ['loader'], // Fetch chunk THEN execute loader = two network waterfalls
    ['component'],
  ],
}

// PREFERRED — loader stays in main bundle (default behavior)
codeSplittingOptions: {
  defaultBehavior: [
    ['component'],
    ['errorComponent'],
    ['notFoundComponent'],
  ],
}
```

### 4. HIGH: Importing Route in code-split files for typed hooks

```tsx
// WRONG — importing Route pulls route config into the lazy chunk
import { Route } from './posts.tsx'
const data = Route.useLoaderData()

// CORRECT — getRouteApi gives typed hooks without pulling in the route
import { getRouteApi } from '@tanstack/react-router'
const routeApi = getRouteApi('/posts')
const data = routeApi.useLoaderData()
```

## Cross-References

- **router-core/data-loading** — Loader splitting decisions affect data loading performance. Splitting the loader adds latency before data can be fetched.
- **router-core/type-safety** — `getRouteApi` is the type-safe way to access hooks from split files.

© TanStack · MIT · TanStack/router

Similar skills

All skills for Frontend and UI →
react-vite-best-practices agent-skills react-vite-best-practices — a skill with 23 rules for optimizing React apps built with Vite: build config, code splitting, HMR, assets, env variables and bundle analysis. Useful when an agent writes or reviews components. CX Codex +1 3,000installs vite-bundle-optimization patterns.dev vite-bundle-optimization is a skill for Claude Code, Codex, Cursor, GitHub Copilot, and Gemini CLI for Vite + React bundle optimization. It activates during build configuration, code splitting, or slow-build diagnosis. CX Codex +1 692installs tanstack-router Claude Skills Maintainers tanstack-router configures type-safe file-based routing in React SPAs and resolves integration issues with TanStack Query or Cloudflare Workers. CX Codex +1 468installs react-performance-optimization NickCrew react-performance-optimization guides React rendering optimization, memoization, code splitting, and list virtualization. Useful when diagnosing slow components or trimming initial bundle size. CX Codex +1 1,900installs web-performance-optimization secondsky web-performance-optimization is a Claude Code skill for improving web app load times and trimming bundle size. It comes into play when configuring caching or tracking Core Web Vitals. CX Codex +1 589installs tanstack-router-react-cursorrules-prompt-file PatrickJS tanstack-router-react-cursorrules-prompt-file enforces TanStack Router v1 patterns in React: file-based routing, Zod search param validation, loaders, and auth guards via beforeLoad. CX Codex +1 ★ 41,178repo stars

From the same set25

The whole set →
server-functions server-functions teaches your coding agent how to build type-safe RPCs in TanStack Start with createServerFn, validate inputs using Zod, and trigger mutations from UI components. CX Codex +1 221installs auth-and-guards auth-and-guards — a skill for protecting routes in TanStack Router. Redirects unauthenticated users, embeds role and permission checks, integrates Auth0, Clerk, Supabase via router context. CX Codex +1 219installs navigation This skill guides TanStack Router navigation with links, programmatic transitions, route preloading, and protection against leaving dirty forms. CX Codex +1 214installs execution-model The execution-model skill teaches agents to separate server and browser code in TanStack Start, with SSR, hydration, imports, and environment variables in view. CX Codex +1 214installs not-found-and-errors not-found-and-errors teaches coding agents to configure 404 boundaries and error components in TanStack Router. It covers throwing notFound() and handling loader failures. CX Codex +1 211installs deployment deployment deploys TanStack Start to Cloudflare Workers, Netlify, Vercel, Node.js, Bun, and Railway. Controls SSR per route, static prerendering, and SEO config. CX Codex +1 210installs path-params path-params — a skill for handling dynamic URL parameters in TanStack Router. Teaches agents to capture variable path segments, set up optional routes, and create patterns with prefixes and suffixes. CX Codex +1 208installs middleware Covers TanStack Start middleware: createMiddleware, context chaining via next(), sendContext for cross-boundary transfers, and global registration in src/start.ts. CX Codex +1 206installs

Project sponsors

Companies that keep this analytics open