react-web-advanced
Web-specific React patterns for type-safe file-based routing, route-level data loading, server-side rendering, search param validation, code splitting, and list virtualization. Use when building React web apps with route loaders, SSR streaming, validated search params, lazy route splitting, or virtualizing large DOM lists. Do not use for React Native apps — use react-native-advanced instead.
What this skill does
# React Web Advanced: TanStack Router, Start & Virtual
Web-specific patterns for React apps built on the TanStack Router + Start + Virtual stack.
This skill extends `react-advanced` (core cross-platform patterns). Read that skill first for
React Query, XState, Zustand, Zod, TanStack Form, and TanStack Table conventions.
## Web Architecture
The web stack adds three layers on top of the shared core:
| Layer | Library | Responsibility |
| ------------------- | ---------------- | --------------------------------------------------- |
| Routing + URL state | TanStack Router | Type-safe navigation, search params, route loaders |
| Full-stack boundary | TanStack Start | Server functions (`createServerFn`), SSR, streaming |
| Large lists | TanStack Virtual | Virtualized rendering for 1000+ items |
### The golden rule: `queryOptions` as single source of truth
Define query options once, import everywhere — loaders, components, invalidation:
```typescript
// queries/posts.ts
export const postsQueryOptions = queryOptions({
queryKey: ["posts"],
queryFn: fetchPosts,
staleTime: 30_000,
});
```
### Router + React Query wiring
The router receives `QueryClient` as context — the single integration point:
```typescript
const router = createRouter({
routeTree,
context: { queryClient },
defaultPreload: "intent",
defaultPreloadStaleTime: 0, // Let React Query manage staleness
});
declare module "@tanstack/react-router" {
interface Register {
router: typeof router;
}
}
```
`defaultPreloadStaleTime: 0` is intentional — without it, the router caches loader results
independently, causing React Query's `staleTime` to be ignored during preloads.
---
## Route Loader + React Query Pattern
### ensureQueryData for blocking, prefetchQuery for non-blocking
```typescript
export const Route = createFileRoute('/posts/$postId')({
loader: async ({ context: { queryClient }, params }) => {
// Fire-and-forget secondary data
queryClient.prefetchQuery(commentsQueryOptions(params.postId))
// Block route render until critical data is ready
await queryClient.ensureQueryData(postQueryOptions(params.postId))
},
component: PostDetail,
})
function PostDetail() {
const { postId } = Route.useParams()
// Data guaranteed in cache — instant, no loading state
const { data: post } = useSuspenseQuery(postQueryOptions(postId))
return <h1>{post.title}</h1>
}
```
### Avoid waterfall requests
Prefetch all independent data in route loaders using `Promise.all`:
```typescript
loader: async ({ context: { queryClient }, params }) => {
await Promise.all([
queryClient.ensureQueryData(userQueryOptions(params.id)),
queryClient.ensureQueryData(permissionsQueryOptions(params.id)),
]);
// Fire-and-forget for non-critical
queryClient.prefetchQuery(activityQueryOptions(params.id));
};
```
- Never fetch data in `useEffect` that could go in a route loader
- Parent and child route loaders run concurrently by default
---
## Performance Patterns
### React Compiler (React 19+)
With the compiler enabled:
- **Do not** manually wrap components in `React.memo`
- **Do not** manually use `useMemo` / `useCallback` for performance
- **Do** write idiomatic React — the compiler handles memoization
- **Do** ensure code follows Rules of React (no mutation during render)
Manual `useMemo`/`useCallback` remain useful only for controlling effect dependencies.
### Suspense boundaries placement
- Route-level boundaries: use `pendingComponent` / `errorComponent` on route definitions
- Within routes: wrap non-blocking data in `<Suspense>` individually
- Group co-dependent queries under one `<Suspense>` so they resolve together
- Independent queries get separate `<Suspense>` boundaries
### Code splitting
- Split routes using `.lazy()` or `.lazy.tsx` files — critical config (loader, params)
stays in the main file, component/UI splits into the lazy file
- Use `React.lazy` for heavy on-demand components (rich editors, charts)
- Machine definitions auto-split since they are separate `.ts` files
---
## File Organization
```text
src/
routes/ # TanStack Router file-based routes
__root.tsx # Root layout, router context type
(auth)/ # Route group — no URL impact
(app)/
users/
$userId.tsx
$userId.lazy.tsx # Component-only code split
-components/ # "-" prefix excludes from route tree
queries/ # queryOptions definitions — one file per entity
mutations/ # useMutation wrappers
machines/ # XState machine definitions (pure TS, no React)
stores/ # Zustand stores
serverFns/ # TanStack Start server functions
components/
ui/ # Design system primitives
shared/ # Cross-feature shared components
lib/
query-client.ts # QueryClient singleton
router.ts # Router singleton
test/
setup.ts # Vitest setup
test-utils.tsx # renderWithProviders
mocks/handlers.ts # MSW handlers
```
Key conventions:
- Route-specific components use `-` prefix directories to avoid route tree inclusion
- Pathless route groups `(name)/` for organization without URL impact
- `.lazy.tsx` files export component/pendingComponent/errorComponent only
- Co-locate test files next to source (`.test.ts` / `.test.tsx`)
---
## Common Pitfalls
1. **Wrong property order in `createFileRoute`** — must be
`validateSearch -> loaderDeps -> beforeLoad -> loader` for TypeScript inference.
Install `@tanstack/eslint-plugin-router` with `create-route-property-order` rule.
2. **Returning entire search in `loaderDeps`** — invalidates cache on any param change.
Extract only the deps the loader uses.
3. **`preload="intent"` without React Query cache** — preloaded data is discarded if user
doesn't navigate. Combine with React Query's `ensureQueryData` for cache persistence.
4. **Not registering the router** — without `declare module Register`, everything is `any`.
5. **Forgetting `<Suspense>` around `<Await>`** — runtime error without a Suspense ancestor.
6. **`defaultPreloadStaleTime` not set to 0** — Router's default staleTime overrides React
Query's staleTime during preloads, causing stale data to be served.
7. **`useLoaderData` in `notFoundComponent`** — not valid. Use `Route.useParams()` or
pass data via `throw notFound({ data: ... })`.
8. **Building all pages before verifying auth flow** — implement and verify the auth flow
first (login → session cookie → protected route guard → redirect) end-to-end before
building feature pages. Auth integration bugs hide behind each other (7+ layers deep).
See `references/ssr-auth.md`.
9. **`defaultPreload: "intent"` triggering auth checks on hover** — with intent preloading,
`beforeLoad` fires on every link hover. If `beforeLoad` does auth validation, every hover
triggers a session check. Disable intent preloading during auth debugging, or make auth
checks cache-aware (`queryClient.getQueryData(sessionKey)` before fetching).
10. **Blanket `invalidateQueries()` cascading through auth hooks** —
`queryClient.invalidateQueries()` with no key filter invalidates everything, including
session queries. Auth reactive hooks refetch, components re-render, `beforeLoad` re-runs.
Always scope invalidation to the specific entity query key.
See `references/integration.md` for query key namespacing patterns.
11. **Auth nanostores re-rendering on every API mutation** — libraries like Better Auth
use nanostores internally. Every successful mutation toggles signals, causing all
`useSession()`/`useActiveOrganization()` subscribers to re-render synchronously.
Combined with TanStack Router, this creates infinite re-render loops. Replace auth
hooks with ReacRelated in Web Dev
generating-lwc-components
IncludedLightning Web Components with PICKLES methodology and 165-point scoring. Use this skill when the user creates or edits LWC components, builds wire service patterns, or writes Jest tests for LWC. TRIGGER when: user creates/edits LWC components, touches lwc/**/*.js, .html, .css, .js-meta.xml files, or asks about wire service, SLDS, or Jest LWC tests. DO NOT TRIGGER when: Apex classes (use generating-apex), Aura components, or Visualforce.
tanstack-query
IncludedManage server state in React with TanStack Query v5. Set up queries with useQuery, mutations with useMutation, configure QueryClient caching strategies, implement optimistic updates, and handle infinite scroll with useInfiniteQuery. Use when: setting up data fetching in React projects, migrating from v4 to v5, or fixing object syntax required errors, query callbacks removed issues, cacheTime renamed to gcTime, isPending vs isLoading confusion, keepPreviousData removed problems.
document-processor-api
IncludedProcess documents with Nutrient DWS. Use when the user wants to generate PDFs from HTML or URLs, convert Office/images/PDFs, assemble or split packets, OCR scans, extract text/tables/key-value pairs, redact PII, watermark, sign, fill forms, optimize PDFs, or produce compliance outputs like PDF/A or PDF/UA. Triggers include convert to PDF, merge these PDFs, OCR this scan, extract tables, redact PII, sign this PDF, make this PDF/A, or linearize for web delivery.
nutrient-document-processing
IncludedProcess documents with Nutrient DWS. Use when the user wants to generate PDFs from HTML or URLs, convert Office/images/PDFs, assemble or split packets, OCR scans, extract text/tables/key-value pairs, redact PII, watermark, sign, fill forms, optimize PDFs, or produce compliance outputs like PDF/A or PDF/UA. Triggers include convert to PDF, merge these PDFs, OCR this scan, extract tables, redact PII, sign this PDF, make this PDF/A, or linearize for web delivery.
tanstack-query
IncludedManage server state in React with TanStack Query v5. Covers useMutationState, simplified optimistic updates, throwOnError, network mode (offline/PWA), and infiniteQueryOptions. Use when setting up data fetching, fixing v4→v5 migration errors (object syntax, gcTime, isPending, keepPreviousData), or debugging SSR/hydration issues with streaming server components.
accelint-nextjs-best-practices
IncludedNext.js performance optimization and best practices. Use when writing Next.js code (App Router or Pages Router); implementing Server Components, Server Actions, or API routes; optimizing RSC serialization, data fetching, or server-side rendering; reviewing Next.js code for performance issues; fixing authentication in Server Actions; or implementing Suspense boundaries, parallel data fetching, or request deduplication.