SKILL.md
SKILL.mdBrowse 14 files
2,123 tokens
8,608 bytes
Token encoding: o200k_base
Snapshot 8e164d2
1---2name: react-start3description: >-4 React bindings for TanStack Start: createStart, StartClient,5 StartServer, React-specific imports, re-exports from6 @tanstack/react-router, full project setup with React, useServerFn7 hook.8metadata:9 type: framework10 library: tanstack-start11 library_version: '1.168.32'12 framework: react13requires:14 - start-core15sources:16 - TanStack/router:packages/react-start/src17 - TanStack/router:docs/start/framework/react/build-from-scratch.md18---19 20# React Start (`@tanstack/react-start`)21 22This is the React Start entry skill. Use the workflow below, then load only the package skill that owns the boundary you are changing. Do not read `start-core`, Router Core, and React Router manuals in full before starting.23 24For React Server Components patterns, see [react-start/server-components](./server-components/SKILL.md).25 26> **CRITICAL**: All code is ISOMORPHIC by default. Loaders run on BOTH server and client. Use `createServerFn` for server-only logic.27 28> **CRITICAL**: Do not confuse `@tanstack/react-start` with Next.js or Remix. They are completely different frameworks with different APIs.29 30> **CRITICAL**: Types are FULLY INFERRED. Never cast, never annotate inferred values.31 32## Full-Stack Workflow33 341. Define the route and component with `createFileRoute`.352. Put private or server-only reads and writes in `createServerFn`; call reads directly from loaders.363. Use `useServerFn` for component mutations, then invalidate the router or query cache after the write resolves.374. Enforce auth in every private server function or server route. Add `beforeLoad` separately for navigation UX.385. Run the initial SSR path, client navigation, mutation plus reload, direct anonymous endpoint request, runtime response assertion, type tests, and production build.39 40Load `start-core/server-routes` instead of `server-functions` only when a raw HTTP endpoint is required. Load `router-core/*` only for the specific routing concern involved, such as params or search validation.41 42## Package API Surface43 44`@tanstack/react-start` re-exports everything from `@tanstack/start-client-core` plus:45 46- `useServerFn` — React hook for calling server functions from components47 48All core APIs (`createServerFn`, `createMiddleware`, `createStart`, `createIsomorphicFn`, `createServerOnlyFn`, `createClientOnlyFn`) are available from `@tanstack/react-start`.49 50Server utilities (`getRequest`, `getRequestHeader`, `setResponseHeader`, `setResponseHeaders`, `setResponseStatus`) are imported from `@tanstack/react-start/server`.51 52## Full Project Setup53 54### 1. Install Dependencies55 56```bash57npm i @tanstack/react-start @tanstack/react-router react react-dom58npm i -D vite @vitejs/plugin-react typescript @types/react @types/react-dom59```60 61### 2. package.json62 63```json64{65 "type": "module",66 "scripts": {67 "dev": "vite dev",68 "build": "vite build",69 "start": "node .output/server/index.mjs"70 }71}72```73 74### 3. tsconfig.json75 76```json77{78 "compilerOptions": {79 "jsx": "react-jsx",80 "moduleResolution": "Bundler",81 "module": "ESNext",82 "target": "ES2022",83 "skipLibCheck": true,84 "strictNullChecks": true85 }86}87```88 89### 4. vite.config.ts90 91```ts92import { defineConfig } from 'vite'93import { tanstackStart } from '@tanstack/react-start/plugin/vite'94import viteReact from '@vitejs/plugin-react'95 96export default defineConfig({97 plugins: [98 tanstackStart(), // MUST come before react()99 viteReact(),100 ],101})102```103 104### 5. Router Factory (src/router.tsx)105 106```tsx107import { createRouter } from '@tanstack/react-router'108import { routeTree } from './routeTree.gen'109 110export function getRouter() {111 const router = createRouter({112 routeTree,113 scrollRestoration: true,114 })115 return router116}117```118 119### 6. Root Route (src/routes/\_\_root.tsx)120 121```tsx122import type { ReactNode } from 'react'123import {124 Outlet,125 createRootRoute,126 HeadContent,127 Scripts,128} from '@tanstack/react-router'129 130export const Route = createRootRoute({131 head: () => ({132 meta: [133 { charSet: 'utf-8' },134 { name: 'viewport', content: 'width=device-width, initial-scale=1' },135 { title: 'My TanStack Start App' },136 ],137 }),138 component: RootComponent,139})140 141function RootComponent() {142 return (143 <RootDocument>144 <Outlet />145 </RootDocument>146 )147}148 149function RootDocument({ children }: Readonly<{ children: ReactNode }>) {150 return (151 <html>152 <head>153 <HeadContent />154 </head>155 <body>156 {children}157 <Scripts />158 </body>159 </html>160 )161}162```163 164### 7. Index Route (src/routes/index.tsx)165 166```tsx167import { createFileRoute } from '@tanstack/react-router'168import { createServerFn } from '@tanstack/react-start'169 170const getGreeting = createServerFn({ method: 'GET' }).handler(async () => {171 return 'Hello from TanStack Start!'172})173 174export const Route = createFileRoute('/')({175 loader: () => getGreeting(),176 component: HomePage,177})178 179function HomePage() {180 const greeting = Route.useLoaderData()181 return <h1>{greeting}</h1>182}183```184 185## useServerFn Hook186 187Use `useServerFn` to call server functions from React components with proper integration:188 189```tsx190import { createServerFn, useServerFn } from '@tanstack/react-start'191 192const updatePost = createServerFn({ method: 'POST' })193 .validator((data: { id: string; title: string }) => data)194 .handler(async ({ data }) => {195 await db.posts.update(data.id, { title: data.title })196 return { success: true }197 })198 199function EditPostForm({ postId }: { postId: string }) {200 const updatePostFn = useServerFn(updatePost)201 const [title, setTitle] = useState('')202 203 return (204 <form205 onSubmit={async (e) => {206 e.preventDefault()207 await updatePostFn({ data: { id: postId, title } })208 }}209 >210 <input value={title} onChange={(e) => setTitle(e.target.value)} />211 <button type="submit">Save</button>212 </form>213 )214}215```216 217## Global Start Configuration (src/start.ts)218 219```tsx220import { createStart, createMiddleware } from '@tanstack/react-start'221 222const requestLogger = createMiddleware().server(async ({ next, request }) => {223 console.log(`${request.method} ${request.url}`)224 return next()225})226 227export const startInstance = createStart(() => ({228 requestMiddleware: [requestLogger],229}))230```231 232## React-Specific Components233 234All routing components from `@tanstack/react-router` work in Start:235 236- `<RouterProvider>` — not needed in Start (handled automatically)237- `<Outlet>` — renders matched child route238- `<Link>` — type-safe navigation239- `<Navigate>` — declarative redirect240- `<HeadContent>` — renders head tags (must be in `<head>`)241- `<Scripts>` — renders body scripts (must be in `<body>`)242- `<Await>` — renders deferred data with Suspense243- `<ClientOnly>` — renders children only after hydration244- `<CatchBoundary>` — error boundary245 246## Hooks Reference247 248All hooks from `@tanstack/react-router` work in Start:249 250- `useRouter()` — router instance251- `useRouterState()` — subscribe to router state252- `useNavigate()` — programmatic navigation253- `useSearch({ from })` — validated search params254- `useParams({ from })` — path params255- `useLoaderData({ from })` — loader data256- `useMatch({ from })` — full route match257- `useRouteContext({ from })` — route context258- `Route.useLoaderData()` — typed loader data (preferred in route files)259- `Route.useSearch()` — typed search params (preferred in route files)260 261## Common Mistakes262 263### 1. CRITICAL: Importing from wrong package264 265```tsx266// WRONG — this is the SPA router, NOT Start267import { createServerFn } from '@tanstack/react-router'268 269// CORRECT — server functions come from react-start270import { createServerFn } from '@tanstack/react-start'271 272// CORRECT — routing APIs come from react-router (re-exported by Start too)273import { createFileRoute, Link } from '@tanstack/react-router'274```275 276### 2. HIGH: Using React hooks in beforeLoad or loader277 278```tsx279// WRONG — beforeLoad/loader are NOT React components280beforeLoad: () => {281 const auth = useAuth() // React hook, cannot be used here282}283 284// CORRECT — pass state via router context285const rootRoute = createRootRouteWithContext<{ auth: AuthState }>()({})286```287 288### 3. HIGH: Missing Scripts component289 290Without `<Scripts />` in the root route's `<body>`, client JavaScript doesn't load and the app won't hydrate.291 292## Cross-References293 294- [start-core](../../../start-client-core/skills/start-core/SKILL.md) — core Start concepts295- [router-core](../../../router-core/skills/router-core/SKILL.md) — routing fundamentals296- [react-router](../../../react-router/skills/react-router/SKILL.md) — React Router hooks and components297 Discovery context
Discovered by repository scan. No exact path reference found in the snapshot’s root AGENTS.md.