tanstack-router
БесплатноБез исполняемых скриптовНе проверенType-safe, file-based routing for React with TanStack Router. Use when defining routes with createFileRoute, validating search params with Zod, writing route…
от Mindrally★ 323 звезды на GitHubОб этом скилле
TanStack Router
TanStack Router is a fully type-safe router for React that treats routes, loaders, params, and search params as first-class typed data rather than untyped strings.
Workflow for Adding a New Route
- Create the route file — Add a file under
src/routes/following the file-based routing convention (see below). - Define the route — Export
RoutefromcreateFileRoute('/path')({...})withcomponent, and optionallyloader,validateSearch,beforeLoad,errorComponent, andpendingComponent. - Validate search params — If the route reads query params, define a Zod schema and pass it as
validateSearch. - Load data — Fetch data in
loader, not in a componentuseEffect; integrate with TanStack Query viaqueryClient.ensureQueryDatawhen caching is needed. - Guard access — Add
beforeLoadchecks (e.g. auth) thatthrow redirect({ to: '/login' })when a precondition fails. - Link to the route — Navigate with
<Link to="/path" params={...} search={...}>so the compiler validates params and search at every call site. - Regenerate the route tree — Ensure
routeTree.gen.tsis regenerated (automatic under the Vite plugin's dev server / build) before running or building the app.
Core Principles
- TanStack Router is 100% type-safe — lean on TypeScript generics for params, search params, and loader data instead of manual casting.
- Prefer file-based routing with
@tanstack/router-vite-plugin(or@tanstack/router-plugin/vite) for scalability over manually constructed route trees. - Always define routes with
createFileRoute(leaf/nested routes) orcreateRootRoute/createRootRouteWithContext(root). - Route data loading belongs in
loaderfunctions, not in componentuseEffect— this enables preloading, parallel loading, and pending/error states. - Search params are first-class state — always define their schema with Zod (or another standard-schema validator) so they are typed and validated on every read.
File-Based Route Conventions
src/routes/
__root.tsx ← Root layout
index.tsx ← / route
posts/
index.tsx ← /posts
$postId.tsx ← /posts/:postId (dynamic segment)
_layout.tsx ← Layout route (no path segment)
_auth/ ← Pathless auth layout group
dashboard.tsx
- A leading underscore on a segment (
_layout,_auth) creates a pathless layout route used purely for grouping/shared UI. - A
$prefix ($postId) marks a dynamic path segment, matchingRoute.useParams(). index.tsxinside a folder matches the folder's own path with no additional segment.
Route Definition
export const Route = createFileRoute('/posts/$postId')({
loader: async ({ params }) => fetchPost(params.postId),
component: PostComponent,
errorComponent: ({ error }) => <ErrorBanner message={error.message} />,
pendingComponent: () => <PostSkeleton />,
})
function PostComponent() {
const post = Route.useLoaderData() // type-safe
const { postId } = Route.useParams() // type-safe
return <div>{post.title}</div>
}
errorComponentrenders when the loader throws;pendingComponentrenders while the loader is in flight (subject todefaultPendingMs).- Loader return values and thrown errors are both fully typed and flow into
useLoaderData()anderrorComponentrespectively.
Type-Safe Search Params
- Always define search params with Zod and
validateSearch. - Access them with
Route.useSearch()— never readwindow.location.searchorURLSearchParamsdirectly, which bypasses type safety and validation.
const searchSchema = z.object({
page: z.number().int().min(1).default(1),
q: z.string().optional(),
})
export const Route = createFileRoute('/search')({
validateSearch: searchSchema,
component: SearchPage,
})
function SearchPage() {
const { page, q } = Route.useSearch()
const navigate = Route.useNavigate()
return (
<button onClick={() => navigate({ search: (prev) => ({ ...prev, page: page + 1 }) })}>
Next page
</button>
)
}
Navigation
- Use
<Link>for internal navigation — never a raw<a href>, which triggers a full page reload and loses client-side routing state. - Always pass typed
paramsandsearch; the TypeScript compiler catches missing or mistyped route params at build time.
<Link to="/posts/$postId" params={{ postId: '123' }}>View Post</Link>
<Link to="/search" search={{ page: 1, q: 'react' }}>Search</Link>
Loaders + TanStack Query Integration
- Put the
QueryClientin router context so loaders can prefetch and cache through TanStack Query rather than duplicating fetch logic. - Use
ensureQueryData(notfetchQuery) in loaders so an already-cached query is reused instead of refetched.
export const Route = createFileRoute('/posts')({
loader: ({ context: { queryClient } }) =>
queryClient.ensureQueryData(postsQueryOptions()),
component: PostsPa
Установить tanstack-router в Claude Code и Claude Desktop
Зарегайся, чтобы установить скилл
Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.
- Открой команду установки в одну строку
- Сохраняй скиллы в синхронизируемую библиотеку
- Уведомления, когда скиллы обновляются
Разрешённые инструменты
Инструменты, которые скиллу разрешено вызывать.
Без ограничений — скилл может использовать любой инструмент.
FAQ
Что делает скилл tanstack-router?
Type-safe, file-based routing for React with TanStack Router. Use when defining routes with createFileRoute, validating search params with Zod, writing route loaders, setting up auth guards with beforeLoad, integrating TanStack Query into loaders, or configuring router context and preloading.
Как установить скилл tanstack-router?
Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.
Скилл tanstack-router запускает скрипты?
Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.
Похожие скиллы
doc-coauthoring
Guide users through a structured workflow for co-authoring documentation. Use when user wants to write documentation, proposals, technical specs, decision…
от Anthropicacademy-guide
Stop and check this skill before finishing any reply to a question about how to use Claude or a Claude product — it recommends matching courses, tutorials…
от Anthropicinternal-comms
A set of resources to help me write all kinds of internal communications, using the formats that my company likes to use. Claude should use this skill…
от Anthropicskill-development
This skill should be used when the user wants to "create a skill", "add a skill to plugin", "write a new skill", "improve skill description", "organize skill…
от Anthropic