diff --git a/.ai/README.md b/.ai/README.md index 38adffd9..70a8841f 100644 --- a/.ai/README.md +++ b/.ai/README.md @@ -11,6 +11,7 @@ future coding agent read the same instructions from here. | Directory | Contains | | ------------- | --------------------------------------------------------------------- | | `skills/` | Reusable **operational playbooks** — how to do a kind of work well. | +| `references/` | Supporting material loaded only when a skill needs it. | | `roles/` | Reusable **agent personas** — focused roles with a mission and scope. | | `workflows/` | **Task workflows** — how to execute common end-to-end tasks. | @@ -55,6 +56,11 @@ Area skills: | [prompt-rendering](skills/prompt-rendering.md) | Prompt templates and rendering. | | [sidecar-auth-context](skills/sidecar-auth-context.md) | Plugin context and protected-node access. | | [mcp-tools](skills/mcp-tools.md) | Tool plugins and MCP servers. | +| [vercel-react-best-practices](skills/vercel-react-best-practices.md) | React chat widget implementation, review, and performance. | + +The Vercel skill includes 70 vendored rules under +`references/vercel-react-best-practices/rules/`. Its canonical entrypoint records +the upstream revision and license; generated adapters use the same references. ### `roles/` — agent personas diff --git a/.ai/references/vercel-react-best-practices/rules/advanced-effect-event-deps.md b/.ai/references/vercel-react-best-practices/rules/advanced-effect-event-deps.md new file mode 100644 index 00000000..24d901b6 --- /dev/null +++ b/.ai/references/vercel-react-best-practices/rules/advanced-effect-event-deps.md @@ -0,0 +1,56 @@ +--- +title: Do Not Put Effect Events in Dependency Arrays +impact: LOW +impactDescription: avoids unnecessary effect re-runs and lint errors +tags: advanced, hooks, useEffectEvent, dependencies, effects +--- + +## Do Not Put Effect Events in Dependency Arrays + +Effect Event functions do not have a stable identity. Their identity intentionally changes on every render. Do not include the function returned by `useEffectEvent` in a `useEffect` dependency array. Keep the actual reactive values as dependencies and call the Effect Event from inside the effect body or subscriptions created by that effect. + +**Incorrect (Effect Event added as a dependency):** + +```tsx +import { useEffect, useEffectEvent } from 'react' + +function ChatRoom({ roomId, onConnected }: { + roomId: string + onConnected: () => void +}) { + const handleConnected = useEffectEvent(onConnected) + + useEffect(() => { + const connection = createConnection(roomId) + connection.on('connected', handleConnected) + connection.connect() + + return () => connection.disconnect() + }, [roomId, handleConnected]) +} +``` + +Including the Effect Event in dependencies makes the effect re-run every render and triggers the React Hooks lint rule. + +**Correct (depend on reactive values, not the Effect Event):** + +```tsx +import { useEffect, useEffectEvent } from 'react' + +function ChatRoom({ roomId, onConnected }: { + roomId: string + onConnected: () => void +}) { + const handleConnected = useEffectEvent(onConnected) + + useEffect(() => { + const connection = createConnection(roomId) + connection.on('connected', handleConnected) + connection.connect() + + return () => connection.disconnect() + }, [roomId]) +} +``` + +Reference: [React useEffectEvent: Effect Event in deps](https://react.dev/reference/react/useEffectEvent#effect-event-in-deps) diff --git a/.ai/references/vercel-react-best-practices/rules/advanced-event-handler-refs.md b/.ai/references/vercel-react-best-practices/rules/advanced-event-handler-refs.md new file mode 100644 index 00000000..75916ab4 --- /dev/null +++ b/.ai/references/vercel-react-best-practices/rules/advanced-event-handler-refs.md @@ -0,0 +1,55 @@ +--- +title: Store Event Handlers in Refs +impact: LOW +impactDescription: stable subscriptions +tags: advanced, hooks, refs, event-handlers, optimization +--- + +## Store Event Handlers in Refs + +Store callbacks in refs when used in effects that shouldn't re-subscribe on callback changes. + +**Incorrect (re-subscribes on every render):** + +```tsx +function useWindowEvent(event: string, handler: (e) => void) { + useEffect(() => { + window.addEventListener(event, handler) + return () => window.removeEventListener(event, handler) + }, [event, handler]) +} +``` + +**Correct (stable subscription):** + +```tsx +function useWindowEvent(event: string, handler: (e) => void) { + const handlerRef = useRef(handler) + useEffect(() => { + handlerRef.current = handler + }, [handler]) + + useEffect(() => { + const listener = (e) => handlerRef.current(e) + window.addEventListener(event, listener) + return () => window.removeEventListener(event, listener) + }, [event]) +} +``` + +**Alternative: use `useEffectEvent` if you're on latest React:** + +```tsx +import { useEffectEvent } from 'react' + +function useWindowEvent(event: string, handler: (e) => void) { + const onEvent = useEffectEvent(handler) + + useEffect(() => { + window.addEventListener(event, onEvent) + return () => window.removeEventListener(event, onEvent) + }, [event]) +} +``` + +`useEffectEvent` provides a cleaner API for the same pattern. Its returned function is not stable: React returns a new one on every render, so keep it out of dependency arrays (see `advanced-effect-event-deps.md`). The subscription still works because the function registered by the effect, from whichever render, always runs the latest handler with the latest props and state. diff --git a/.ai/references/vercel-react-best-practices/rules/advanced-init-once.md b/.ai/references/vercel-react-best-practices/rules/advanced-init-once.md new file mode 100644 index 00000000..73ee38e5 --- /dev/null +++ b/.ai/references/vercel-react-best-practices/rules/advanced-init-once.md @@ -0,0 +1,42 @@ +--- +title: Initialize App Once, Not Per Mount +impact: LOW-MEDIUM +impactDescription: avoids duplicate init in development +tags: initialization, useEffect, app-startup, side-effects +--- + +## Initialize App Once, Not Per Mount + +Do not put app-wide initialization that must run once per app load inside `useEffect([])` of a component. Components can remount and effects will re-run. Use a module-level guard or top-level init in the entry module instead. + +**Incorrect (runs twice in dev, re-runs on remount):** + +```tsx +function Comp() { + useEffect(() => { + loadFromStorage() + checkAuthToken() + }, []) + + // ... +} +``` + +**Correct (once per app load):** + +```tsx +let didInit = false + +function Comp() { + useEffect(() => { + if (didInit) return + didInit = true + loadFromStorage() + checkAuthToken() + }, []) + + // ... +} +``` + +Reference: [Initializing the application](https://react.dev/learn/you-might-not-need-an-effect#initializing-the-application) diff --git a/.ai/references/vercel-react-best-practices/rules/advanced-use-latest.md b/.ai/references/vercel-react-best-practices/rules/advanced-use-latest.md new file mode 100644 index 00000000..e1a41967 --- /dev/null +++ b/.ai/references/vercel-react-best-practices/rules/advanced-use-latest.md @@ -0,0 +1,41 @@ +--- +title: useEffectEvent for Latest-Value Callbacks +impact: LOW +impactDescription: prevents effect re-runs +tags: advanced, hooks, useEffectEvent, refs, optimization +--- + +## useEffectEvent for Latest-Value Callbacks + +Access latest values in callbacks without adding them to dependency arrays. Prevents effect re-runs while avoiding stale closures. + +The function returned by `useEffectEvent` is not stable: React intentionally returns a new one on every render. Call it only from inside effects, and keep it out of dependency arrays (see `advanced-effect-event-deps.md`). It avoids re-runs because it always reads the latest props and state, not because its identity is stable. + +**Incorrect (effect re-runs on every callback change):** + +```tsx +function SearchInput({ onSearch }: { onSearch: (q: string) => void }) { + const [query, setQuery] = useState('') + + useEffect(() => { + const timeout = setTimeout(() => onSearch(query), 300) + return () => clearTimeout(timeout) + }, [query, onSearch]) +} +``` + +**Correct (using React's useEffectEvent):** + +```tsx +import { useEffectEvent } from 'react'; + +function SearchInput({ onSearch }: { onSearch: (q: string) => void }) { + const [query, setQuery] = useState('') + const onSearchEvent = useEffectEvent(onSearch) + + useEffect(() => { + const timeout = setTimeout(() => onSearchEvent(query), 300) + return () => clearTimeout(timeout) + }, [query]) +} +``` diff --git a/.ai/references/vercel-react-best-practices/rules/async-api-routes.md b/.ai/references/vercel-react-best-practices/rules/async-api-routes.md new file mode 100644 index 00000000..c94dea68 --- /dev/null +++ b/.ai/references/vercel-react-best-practices/rules/async-api-routes.md @@ -0,0 +1,44 @@ +--- +title: Prevent Waterfall Chains in API Routes +impact: CRITICAL +impactDescription: 2-10× improvement +tags: api-routes, server-actions, waterfalls, parallelization +--- + +## Prevent Waterfall Chains in API Routes + +In API routes and Server Actions, start independent operations immediately, even if you don't await them yet. + +**Incorrect (config waits for auth, data waits for both):** + +```typescript +export async function GET(request: Request) { + const session = await auth() + const config = await fetchConfig() + const data = await fetchData(session.user.id) + return Response.json({ data, config }) +} +``` + +**Correct (auth and config start immediately):** + +```typescript +export async function GET(request: Request) { + const sessionPromise = auth() + const configPromise = fetchConfig() + // Mark the early start as handled: if auth fails or returns early, a later + // config rejection must not become an unhandled rejection. + configPromise.catch(() => {}) + const session = await sessionPromise + if (!session) return new Response('Unauthorized', { status: 401 }) + const [config, data] = await Promise.all([ + configPromise, + fetchData(session.user.id) + ]) + return Response.json({ data, config }) +} +``` + +Start work before authentication only when it is safe for an unauthenticated caller to trigger: cheap, free of side effects, and independent of the caller. Otherwise wait for authentication first. + +For operations with more complex dependency chains, use `better-all` to automatically maximize parallelism (see Dependency-Based Parallelization). diff --git a/.ai/references/vercel-react-best-practices/rules/async-cheap-condition-before-await.md b/.ai/references/vercel-react-best-practices/rules/async-cheap-condition-before-await.md new file mode 100644 index 00000000..5799d7f6 --- /dev/null +++ b/.ai/references/vercel-react-best-practices/rules/async-cheap-condition-before-await.md @@ -0,0 +1,37 @@ +--- +title: Check Cheap Conditions Before Async Flags +impact: HIGH +impactDescription: avoids unnecessary async work when a synchronous guard already fails +tags: async, await, feature-flags, short-circuit, conditional +--- + +## Check Cheap Conditions Before Async Flags + +When a branch uses `await` for a flag or remote value and also requires a **cheap synchronous** condition (local props, request metadata, already-loaded state), evaluate the cheap condition **first**. Otherwise you pay for the async call even when the compound condition can never be true. + +This is a specialization of [Defer Await Until Needed](./async-defer-await.md) for `flag && cheapCondition` style checks. + +**Incorrect:** + +```typescript +const someFlag = await getFlag() + +if (someFlag && someCondition) { + // ... +} +``` + +**Correct:** + +```typescript +if (someCondition) { + const someFlag = await getFlag() + if (someFlag) { + // ... + } +} +``` + +This matters when `getFlag` hits the network, a feature-flag service, or `React.cache` / DB work: skipping it when `someCondition` is false removes that cost on the cold path. + +Keep the original order if `someCondition` is expensive, depends on the flag, or you must run side effects in a fixed order. diff --git a/.ai/references/vercel-react-best-practices/rules/async-defer-await.md b/.ai/references/vercel-react-best-practices/rules/async-defer-await.md new file mode 100644 index 00000000..8eada33f --- /dev/null +++ b/.ai/references/vercel-react-best-practices/rules/async-defer-await.md @@ -0,0 +1,82 @@ +--- +title: Defer Await Until Needed +impact: HIGH +impactDescription: avoids blocking unused code paths +tags: async, await, conditional, optimization +--- + +## Defer Await Until Needed + +Move `await` operations into the branches where they're actually used to avoid blocking code paths that don't need them. + +**Incorrect (blocks both branches):** + +```typescript +async function handleRequest(userId: string, skipProcessing: boolean) { + const userData = await fetchUserData(userId) + + if (skipProcessing) { + // Returns immediately but still waited for userData + return { skipped: true } + } + + // Only this branch uses userData + return processUserData(userData) +} +``` + +**Correct (only blocks when needed):** + +```typescript +async function handleRequest(userId: string, skipProcessing: boolean) { + if (skipProcessing) { + // Returns immediately without waiting + return { skipped: true } + } + + // Fetch only when needed + const userData = await fetchUserData(userId) + return processUserData(userData) +} +``` + +**Another example (early return optimization):** + +```typescript +// Incorrect: always fetches permissions +async function updateResource(resourceId: string, userId: string) { + const permissions = await fetchPermissions(userId) + const resource = await getResource(resourceId) + + if (!resource) { + return { error: 'Not found' } + } + + if (!permissions.canEdit) { + return { error: 'Forbidden' } + } + + return await updateResourceData(resource, permissions) +} + +// Correct: fetches only when needed +async function updateResource(resourceId: string, userId: string) { + const resource = await getResource(resourceId) + + if (!resource) { + return { error: 'Not found' } + } + + const permissions = await fetchPermissions(userId) + + if (!permissions.canEdit) { + return { error: 'Forbidden' } + } + + return await updateResourceData(resource, permissions) +} +``` + +This optimization is especially valuable when the skipped branch is frequently taken, or when the deferred operation is expensive. + +For `await getFlag()` combined with a cheap synchronous guard (`flag && someCondition`), see [Check Cheap Conditions Before Async Flags](./async-cheap-condition-before-await.md). diff --git a/.ai/references/vercel-react-best-practices/rules/async-dependencies.md b/.ai/references/vercel-react-best-practices/rules/async-dependencies.md new file mode 100644 index 00000000..0484ebab --- /dev/null +++ b/.ai/references/vercel-react-best-practices/rules/async-dependencies.md @@ -0,0 +1,51 @@ +--- +title: Dependency-Based Parallelization +impact: CRITICAL +impactDescription: 2-10× improvement +tags: async, parallelization, dependencies, better-all +--- + +## Dependency-Based Parallelization + +For operations with partial dependencies, use `better-all` to maximize parallelism. It automatically starts each task at the earliest possible moment. + +**Incorrect (profile waits for config unnecessarily):** + +```typescript +const [user, config] = await Promise.all([ + fetchUser(), + fetchConfig() +]) +const profile = await fetchProfile(user.id) +``` + +**Correct (config and profile run in parallel):** + +```typescript +import { all } from 'better-all' + +const { user, config, profile } = await all({ + async user() { return fetchUser() }, + async config() { return fetchConfig() }, + async profile() { + return fetchProfile((await this.$.user).id) + } +}) +``` + +**Alternative without extra dependencies:** + +We can also create all the promises first, and do `Promise.all()` at the end. + +```typescript +const userPromise = fetchUser() +const profilePromise = userPromise.then(user => fetchProfile(user.id)) + +const [user, config, profile] = await Promise.all([ + userPromise, + fetchConfig(), + profilePromise +]) +``` + +Reference: [https://github.com/shuding/better-all](https://github.com/shuding/better-all) diff --git a/.ai/references/vercel-react-best-practices/rules/async-parallel.md b/.ai/references/vercel-react-best-practices/rules/async-parallel.md new file mode 100644 index 00000000..64133f6c --- /dev/null +++ b/.ai/references/vercel-react-best-practices/rules/async-parallel.md @@ -0,0 +1,28 @@ +--- +title: Promise.all() for Independent Operations +impact: CRITICAL +impactDescription: 2-10× improvement +tags: async, parallelization, promises, waterfalls +--- + +## Promise.all() for Independent Operations + +When async operations have no interdependencies, execute them concurrently using `Promise.all()`. + +**Incorrect (sequential execution, 3 round trips):** + +```typescript +const user = await fetchUser() +const posts = await fetchPosts() +const comments = await fetchComments() +``` + +**Correct (parallel execution, 1 round trip):** + +```typescript +const [user, posts, comments] = await Promise.all([ + fetchUser(), + fetchPosts(), + fetchComments() +]) +``` diff --git a/.ai/references/vercel-react-best-practices/rules/async-suspense-boundaries.md b/.ai/references/vercel-react-best-practices/rules/async-suspense-boundaries.md new file mode 100644 index 00000000..b12794c5 --- /dev/null +++ b/.ai/references/vercel-react-best-practices/rules/async-suspense-boundaries.md @@ -0,0 +1,99 @@ +--- +title: Strategic Suspense Boundaries +impact: HIGH +impactDescription: faster initial paint +tags: async, suspense, streaming, layout-shift +--- + +## Strategic Suspense Boundaries + +Instead of awaiting data in async components before returning JSX, use Suspense boundaries to show the wrapper UI faster while data loads. + +**Incorrect (wrapper blocked by data fetching):** + +```tsx +async function Page() { + const data = await fetchData() // Blocks entire page + + return ( +
+
Sidebar
+
Header
+
+ +
+
Footer
+
+ ) +} +``` + +The entire layout waits for data even though only the middle section needs it. + +**Correct (wrapper shows immediately, data streams in):** + +```tsx +function Page() { + return ( +
+
Sidebar
+
Header
+
+ }> + + +
+
Footer
+
+ ) +} + +async function DataDisplay() { + const data = await fetchData() // Only blocks this component + return
{data.content}
+} +``` + +Sidebar, Header, and Footer render immediately. Only DataDisplay waits for data. + +**Alternative (share promise across components):** + +```tsx +function Page() { + // Start fetch immediately, but don't await + const dataPromise = fetchData() + + return ( +
+
Sidebar
+
Header
+ }> + + + +
Footer
+
+ ) +} + +function DataDisplay({ dataPromise }: { dataPromise: Promise }) { + const data = use(dataPromise) // Unwraps the promise + return
{data.content}
+} + +function DataSummary({ dataPromise }: { dataPromise: Promise }) { + const data = use(dataPromise) // Reuses the same promise + return
{data.summary}
+} +``` + +Both components share the same promise, so only one fetch occurs. Layout renders immediately while both components wait together. + +**When NOT to use this pattern:** + +- Critical data needed for layout decisions (affects positioning) +- SEO-critical content above the fold +- Small, fast queries where suspense overhead isn't worth it +- When you want to avoid layout shift (loading → content jump) + +**Trade-off:** Faster initial paint vs potential layout shift. Choose based on your UX priorities. diff --git a/.ai/references/vercel-react-best-practices/rules/bundle-analyzable-paths.md b/.ai/references/vercel-react-best-practices/rules/bundle-analyzable-paths.md new file mode 100644 index 00000000..8276f156 --- /dev/null +++ b/.ai/references/vercel-react-best-practices/rules/bundle-analyzable-paths.md @@ -0,0 +1,63 @@ +--- +title: Prefer Statically Analyzable Paths +impact: HIGH +impactDescription: avoids accidental broad bundles and file traces +tags: bundle, nextjs, vite, webpack, rollup, esbuild, path +--- + +## Prefer Statically Analyzable Paths + +Build tools work best when import and file-system paths are obvious at build time. If you hide the real path inside a variable or compose it too dynamically, the tool either has to include a broad set of possible files, warn that it cannot analyze the import, or widen file tracing to stay safe. + +Prefer explicit maps or literal paths so the set of reachable files stays narrow and predictable. This is the same rule whether you are choosing modules with `import()` or reading files in server/build code. + +When analysis becomes too broad, the cost is real: +- Larger server bundles +- Slower builds +- Worse cold starts +- More memory use + +### Import Paths + +**Incorrect (the bundler cannot tell what may be imported):** + +```ts +const PAGE_MODULES = { + home: './pages/home', + settings: './pages/settings', +} as const + +const Page = await import(PAGE_MODULES[pageName]) +``` + +**Correct (use an explicit map of allowed modules):** + +```ts +const PAGE_MODULES = { + home: () => import('./pages/home'), + settings: () => import('./pages/settings'), +} as const + +const Page = await PAGE_MODULES[pageName]() +``` + +### File-System Paths + +**Incorrect (a 2-value enum still hides the final path from static analysis):** + +```ts +const baseDir = path.join(process.cwd(), 'content/' + contentKind) +``` + +**Correct (make each final path literal at the callsite):** + +```ts +const baseDir = + kind === ContentKind.Blog + ? path.join(process.cwd(), 'content/blog') + : path.join(process.cwd(), 'content/docs') +``` + +In Next.js server code, this matters for output file tracing too. `path.join(process.cwd(), someVar)` can widen the traced file set because Next.js statically analyze `import`, `require`, and `fs` usage. + +Reference: [Next.js output](https://nextjs.org/docs/app/api-reference/config/next-config-js/output), [Next.js dynamic imports](https://nextjs.org/learn/seo/dynamic-imports), [Vite features](https://vite.dev/guide/features.html), [esbuild API](https://esbuild.github.io/api/), [Rollup dynamic import vars](https://www.npmjs.com/package/@rollup/plugin-dynamic-import-vars), [Webpack dependency management](https://webpack.js.org/guides/dependency-management/) diff --git a/.ai/references/vercel-react-best-practices/rules/bundle-barrel-imports.md b/.ai/references/vercel-react-best-practices/rules/bundle-barrel-imports.md new file mode 100644 index 00000000..22d10501 --- /dev/null +++ b/.ai/references/vercel-react-best-practices/rules/bundle-barrel-imports.md @@ -0,0 +1,60 @@ +--- +title: Avoid Barrel File Imports +impact: CRITICAL +impactDescription: 200-800ms import cost, slow builds +tags: bundle, imports, tree-shaking, barrel-files, performance +--- + +## Avoid Barrel File Imports + +Import directly from source files instead of barrel files to avoid loading thousands of unused modules. **Barrel files** are entry points that re-export multiple modules (e.g., `index.js` that does `export * from './module'`). + +Popular icon and component libraries can have **up to 10,000 re-exports** in their entry file. For many React packages, **it takes 200-800ms just to import them**, affecting both development speed and production cold starts. + +**Why tree-shaking doesn't help:** When a library is marked as external (not bundled), the bundler can't optimize it. If you bundle it to enable tree-shaking, builds become substantially slower analyzing the entire module graph. + +**Incorrect (imports entire library):** + +```tsx +import { Check, X, Menu } from 'lucide-react' +// Loads 1,583 modules, takes ~2.8s extra in dev +// Runtime cost: 200-800ms on every cold start + +import { Button, TextField } from '@mui/material' +// Loads 2,225 modules, takes ~4.2s extra in dev +``` + +**Correct - Next.js 13.5+ (recommended):** + +```js +// next.config.js - automatically optimizes barrel imports at build time +module.exports = { + experimental: { + optimizePackageImports: ['lucide-react', '@mui/material'] + } +} +``` + +```tsx +// Keep the standard imports - Next.js transforms them to direct imports +import { Check, X, Menu } from 'lucide-react' +// Full TypeScript support, no manual path wrangling +``` + +This is the recommended approach because it preserves TypeScript type safety and editor autocompletion while still eliminating the barrel import cost. + +**Correct - Direct imports (non-Next.js projects):** + +```tsx +import Button from '@mui/material/Button' +import TextField from '@mui/material/TextField' +// Loads only what you use +``` + +> **TypeScript warning:** Some libraries (notably `lucide-react`) don't ship `.d.ts` files for their deep import paths. Importing from `lucide-react/dist/esm/icons/check` resolves to an implicit `any` type, causing errors under `strict` or `noImplicitAny`. Prefer `optimizePackageImports` when available, or verify the library exports types for its subpaths before using direct imports. + +These optimizations provide 15-70% faster dev boot, 28% faster builds, 40% faster cold starts, and significantly faster HMR. + +Libraries commonly affected: `lucide-react`, `@mui/material`, `@mui/icons-material`, `@tabler/icons-react`, `react-icons`, `@headlessui/react`, `@radix-ui/react-*`, `lodash`, `ramda`, `date-fns`, `rxjs`, `react-use`. + +Reference: [How we optimized package imports in Next.js](https://vercel.com/blog/how-we-optimized-package-imports-in-next-js) diff --git a/.ai/references/vercel-react-best-practices/rules/bundle-conditional.md b/.ai/references/vercel-react-best-practices/rules/bundle-conditional.md new file mode 100644 index 00000000..dbe98abf --- /dev/null +++ b/.ai/references/vercel-react-best-practices/rules/bundle-conditional.md @@ -0,0 +1,31 @@ +--- +title: Conditional Module Loading +impact: HIGH +impactDescription: loads large data only when needed +tags: bundle, conditional-loading, lazy-loading +--- + +## Conditional Module Loading + +Load large data or modules only when a feature is activated. + +**Example (lazy-load animation frames):** + +```tsx +function AnimationPlayer({ enabled, setEnabled }: { enabled: boolean; setEnabled: React.Dispatch> }) { + const [frames, setFrames] = useState(null) + + useEffect(() => { + if (enabled && !frames) { + import('./animation-frames.js') + .then(mod => setFrames(mod.frames)) + .catch(() => setEnabled(false)) + } + }, [enabled, frames, setEnabled]) + + if (!frames) return + return +} +``` + +The dynamic `import()` lets the bundler place the frames in a separate chunk that the browser downloads only when the feature is enabled. Effects never run during server rendering, so no `typeof window` check is needed here. Such a check also would not keep the chunk out of a server build; bundling is decided by the `import()` itself and the bundler configuration. diff --git a/.ai/references/vercel-react-best-practices/rules/bundle-defer-third-party.md b/.ai/references/vercel-react-best-practices/rules/bundle-defer-third-party.md new file mode 100644 index 00000000..db041d15 --- /dev/null +++ b/.ai/references/vercel-react-best-practices/rules/bundle-defer-third-party.md @@ -0,0 +1,49 @@ +--- +title: Defer Non-Critical Third-Party Libraries +impact: MEDIUM +impactDescription: loads after hydration +tags: bundle, third-party, analytics, defer +--- + +## Defer Non-Critical Third-Party Libraries + +Analytics, logging, and error tracking don't block user interaction. Load them after hydration. + +**Incorrect (blocks initial bundle):** + +```tsx +import { Analytics } from '@vercel/analytics/react' + +export default function RootLayout({ children }) { + return ( + + + {children} + + + + ) +} +``` + +**Correct (loads after hydration):** + +```tsx +import dynamic from 'next/dynamic' + +const Analytics = dynamic( + () => import('@vercel/analytics/react').then(m => m.Analytics), + { ssr: false } +) + +export default function RootLayout({ children }) { + return ( + + + {children} + + + + ) +} +``` diff --git a/.ai/references/vercel-react-best-practices/rules/bundle-dynamic-imports.md b/.ai/references/vercel-react-best-practices/rules/bundle-dynamic-imports.md new file mode 100644 index 00000000..60b62695 --- /dev/null +++ b/.ai/references/vercel-react-best-practices/rules/bundle-dynamic-imports.md @@ -0,0 +1,35 @@ +--- +title: Dynamic Imports for Heavy Components +impact: CRITICAL +impactDescription: directly affects TTI and LCP +tags: bundle, dynamic-import, code-splitting, next-dynamic +--- + +## Dynamic Imports for Heavy Components + +Use `next/dynamic` to lazy-load large components not needed on initial render. + +**Incorrect (Monaco bundles with main chunk ~300KB):** + +```tsx +import { MonacoEditor } from './monaco-editor' + +function CodePanel({ code }: { code: string }) { + return +} +``` + +**Correct (Monaco loads on demand):** + +```tsx +import dynamic from 'next/dynamic' + +const MonacoEditor = dynamic( + () => import('./monaco-editor').then(m => m.MonacoEditor), + { ssr: false } +) + +function CodePanel({ code }: { code: string }) { + return +} +``` diff --git a/.ai/references/vercel-react-best-practices/rules/bundle-preload.md b/.ai/references/vercel-react-best-practices/rules/bundle-preload.md new file mode 100644 index 00000000..d736418a --- /dev/null +++ b/.ai/references/vercel-react-best-practices/rules/bundle-preload.md @@ -0,0 +1,49 @@ +--- +title: Preload Based on User Intent +impact: MEDIUM +impactDescription: reduces perceived latency +tags: bundle, preload, user-intent, hover +--- + +## Preload Based on User Intent + +Preload heavy bundles before they're needed to reduce perceived latency. + +**Example (preload on hover/focus):** + +```tsx +function EditorButton({ onClick }: { onClick: () => void }) { + // Event handlers only run in the browser + const preload = () => { + void import('./monaco-editor') + } + + return ( + + ) +} +``` + +**Example (preload when feature flag is enabled):** + +```tsx +function FlagsProvider({ children, flags }: Props) { + useEffect(() => { + if (flags.editorEnabled) { + void import('./monaco-editor').then(mod => mod.init()) + } + }, [flags.editorEnabled]) + + return + {children} + +} +``` + +Event handlers and effects never run during server rendering, so neither example needs a `typeof window` check. Such a check would not keep the module out of a server build either: the dynamic `import()` and the bundler configuration decide chunking (see `bundle-conditional.md`). diff --git a/.ai/references/vercel-react-best-practices/rules/client-event-listeners.md b/.ai/references/vercel-react-best-practices/rules/client-event-listeners.md new file mode 100644 index 00000000..f4d612da --- /dev/null +++ b/.ai/references/vercel-react-best-practices/rules/client-event-listeners.md @@ -0,0 +1,74 @@ +--- +title: Deduplicate Global Event Listeners +impact: LOW +impactDescription: single listener for N components +tags: client, swr, event-listeners, subscription +--- + +## Deduplicate Global Event Listeners + +Use `useSWRSubscription()` to share global event listeners across component instances. + +**Incorrect (N instances = N listeners):** + +```tsx +function useKeyboardShortcut(key: string, callback: () => void) { + useEffect(() => { + const handler = (e: KeyboardEvent) => { + if (e.metaKey && e.key === key) { + callback() + } + } + window.addEventListener('keydown', handler) + return () => window.removeEventListener('keydown', handler) + }, [key, callback]) +} +``` + +When using the `useKeyboardShortcut` hook multiple times, each instance will register a new listener. + +**Correct (N instances = 1 listener):** + +```tsx +import useSWRSubscription from 'swr/subscription' + +// Module-level Map to track callbacks per key +const keyCallbacks = new Map void>>() + +function useKeyboardShortcut(key: string, callback: () => void) { + // Register this callback in the Map + useEffect(() => { + if (!keyCallbacks.has(key)) { + keyCallbacks.set(key, new Set()) + } + keyCallbacks.get(key)!.add(callback) + + return () => { + const set = keyCallbacks.get(key) + if (set) { + set.delete(callback) + if (set.size === 0) { + keyCallbacks.delete(key) + } + } + } + }, [key, callback]) + + useSWRSubscription('global-keydown', () => { + const handler = (e: KeyboardEvent) => { + if (e.metaKey && keyCallbacks.has(e.key)) { + keyCallbacks.get(e.key)!.forEach(cb => cb()) + } + } + window.addEventListener('keydown', handler) + return () => window.removeEventListener('keydown', handler) + }) +} + +function Profile() { + // Multiple shortcuts will share the same listener + useKeyboardShortcut('p', () => { /* ... */ }) + useKeyboardShortcut('k', () => { /* ... */ }) + // ... +} +``` diff --git a/.ai/references/vercel-react-best-practices/rules/client-localstorage-schema.md b/.ai/references/vercel-react-best-practices/rules/client-localstorage-schema.md new file mode 100644 index 00000000..d30a1a7d --- /dev/null +++ b/.ai/references/vercel-react-best-practices/rules/client-localstorage-schema.md @@ -0,0 +1,71 @@ +--- +title: Version and Minimize localStorage Data +impact: MEDIUM +impactDescription: prevents schema conflicts, reduces storage size +tags: client, localStorage, storage, versioning, data-minimization +--- + +## Version and Minimize localStorage Data + +Add version prefix to keys and store only needed fields. Prevents schema conflicts and accidental storage of sensitive data. + +**Incorrect:** + +```typescript +// No version, stores everything, no error handling +localStorage.setItem('userConfig', JSON.stringify(fullUserObject)) +const data = localStorage.getItem('userConfig') +``` + +**Correct:** + +```typescript +const VERSION = 'v2' + +function saveConfig(config: { theme: string; language: string }) { + try { + localStorage.setItem(`userConfig:${VERSION}`, JSON.stringify(config)) + } catch { + // Throws in incognito/private browsing, quota exceeded, or disabled + } +} + +function loadConfig() { + try { + const data = localStorage.getItem(`userConfig:${VERSION}`) + return data ? JSON.parse(data) : null + } catch { + return null + } +} + +// Migration from v1 to v2 +function migrate() { + try { + const v1 = localStorage.getItem('userConfig:v1') + if (v1) { + const old = JSON.parse(v1) + saveConfig({ theme: old.darkMode ? 'dark' : 'light', language: old.lang }) + localStorage.removeItem('userConfig:v1') + } + } catch {} +} +``` + +**Store minimal fields from server responses:** + +```typescript +// User object has 20+ fields, only store what UI needs +function cachePrefs(user: FullUser) { + try { + localStorage.setItem('prefs:v1', JSON.stringify({ + theme: user.preferences.theme, + notifications: user.preferences.notifications + })) + } catch {} +} +``` + +**Always wrap in try-catch:** `getItem()` and `setItem()` throw in incognito/private browsing (Safari, Firefox), when quota exceeded, or when disabled. + +**Benefits:** Schema evolution via versioning, reduced storage size, prevents storing tokens/PII/internal flags. diff --git a/.ai/references/vercel-react-best-practices/rules/client-passive-event-listeners.md b/.ai/references/vercel-react-best-practices/rules/client-passive-event-listeners.md new file mode 100644 index 00000000..29c7eec4 --- /dev/null +++ b/.ai/references/vercel-react-best-practices/rules/client-passive-event-listeners.md @@ -0,0 +1,48 @@ +--- +title: Use Passive Event Listeners for Scrolling Performance +impact: MEDIUM +impactDescription: eliminates scroll delay caused by event listeners +tags: client, event-listeners, scrolling, performance, touch, wheel +--- + +## Use Passive Event Listeners for Scrolling Performance + +Add `{ passive: true }` to touch and wheel event listeners to enable immediate scrolling. Browsers normally wait for listeners to finish to check if `preventDefault()` is called, causing scroll delay. + +**Incorrect:** + +```typescript +useEffect(() => { + const handleTouch = (e: TouchEvent) => console.log(e.touches[0].clientX) + const handleWheel = (e: WheelEvent) => console.log(e.deltaY) + + document.addEventListener('touchstart', handleTouch) + document.addEventListener('wheel', handleWheel) + + return () => { + document.removeEventListener('touchstart', handleTouch) + document.removeEventListener('wheel', handleWheel) + } +}, []) +``` + +**Correct:** + +```typescript +useEffect(() => { + const handleTouch = (e: TouchEvent) => console.log(e.touches[0].clientX) + const handleWheel = (e: WheelEvent) => console.log(e.deltaY) + + document.addEventListener('touchstart', handleTouch, { passive: true }) + document.addEventListener('wheel', handleWheel, { passive: true }) + + return () => { + document.removeEventListener('touchstart', handleTouch) + document.removeEventListener('wheel', handleWheel) + } +}, []) +``` + +**Use passive when:** tracking/analytics, logging, any listener that doesn't call `preventDefault()`. + +**Don't use passive when:** implementing custom swipe gestures, custom zoom controls, or any listener that needs `preventDefault()`. diff --git a/.ai/references/vercel-react-best-practices/rules/client-swr-dedup.md b/.ai/references/vercel-react-best-practices/rules/client-swr-dedup.md new file mode 100644 index 00000000..2a430f27 --- /dev/null +++ b/.ai/references/vercel-react-best-practices/rules/client-swr-dedup.md @@ -0,0 +1,56 @@ +--- +title: Use SWR for Automatic Deduplication +impact: MEDIUM-HIGH +impactDescription: automatic deduplication +tags: client, swr, deduplication, data-fetching +--- + +## Use SWR for Automatic Deduplication + +SWR enables request deduplication, caching, and revalidation across component instances. + +**Incorrect (no deduplication, each instance fetches):** + +```tsx +function UserList() { + const [users, setUsers] = useState([]) + useEffect(() => { + fetch('/api/users') + .then(r => r.json()) + .then(setUsers) + }, []) +} +``` + +**Correct (multiple instances share one request):** + +```tsx +import useSWR from 'swr' + +function UserList() { + const { data: users } = useSWR('/api/users', fetcher) +} +``` + +**For immutable data:** + +```tsx +import { useImmutableSWR } from '@/lib/swr' + +function StaticContent() { + const { data } = useImmutableSWR('/api/config', fetcher) +} +``` + +**For mutations:** + +```tsx +import { useSWRMutation } from 'swr/mutation' + +function UpdateButton() { + const { trigger } = useSWRMutation('/api/user', updateUser) + return +} +``` + +Reference: [https://swr.vercel.app](https://swr.vercel.app) diff --git a/.ai/references/vercel-react-best-practices/rules/js-batch-dom-css.md b/.ai/references/vercel-react-best-practices/rules/js-batch-dom-css.md new file mode 100644 index 00000000..78cb923d --- /dev/null +++ b/.ai/references/vercel-react-best-practices/rules/js-batch-dom-css.md @@ -0,0 +1,107 @@ +--- +title: Avoid Layout Thrashing +impact: MEDIUM +impactDescription: prevents forced synchronous layouts and reduces performance bottlenecks +tags: javascript, dom, css, performance, reflow, layout-thrashing +--- + +## Avoid Layout Thrashing + +Avoid interleaving style writes with layout reads. When you read a layout property (like `offsetWidth`, `getBoundingClientRect()`, or `getComputedStyle()`) between style changes, the browser is forced to trigger a synchronous reflow. + +**This is OK (browser batches style changes):** +```typescript +function updateElementStyles(element: HTMLElement) { + // Each line invalidates style, but browser batches the recalculation + element.style.width = '100px' + element.style.height = '200px' + element.style.backgroundColor = 'blue' + element.style.border = '1px solid black' +} +``` + +**Incorrect (interleaved reads and writes force reflows):** +```typescript +function layoutThrashing(element: HTMLElement) { + element.style.width = '100px' + const width = element.offsetWidth // Forces reflow + element.style.height = '200px' + const height = element.offsetHeight // Forces another reflow +} +``` + +**Correct (batch writes, then read once):** +```typescript +function updateElementStyles(element: HTMLElement) { + // Batch all writes together + element.style.width = '100px' + element.style.height = '200px' + element.style.backgroundColor = 'blue' + element.style.border = '1px solid black' + + // Read after all writes are done (single reflow) + const { width, height } = element.getBoundingClientRect() +} +``` + +**Correct (batch reads, then writes):** +```typescript +function avoidThrashing(element: HTMLElement) { + // Read phase - all layout queries first + const rect1 = element.getBoundingClientRect() + const offsetWidth = element.offsetWidth + const offsetHeight = element.offsetHeight + + // Write phase - all style changes after + element.style.width = '100px' + element.style.height = '200px' +} +``` + +**Better: use CSS classes** +```css +.highlighted-box { + width: 100px; + height: 200px; + background-color: blue; + border: 1px solid black; +} +``` +```typescript +function updateElementStyles(element: HTMLElement) { + element.classList.add('highlighted-box') + + const { width, height } = element.getBoundingClientRect() +} +``` + +**React example:** +```tsx +// Incorrect: interleaving style changes with layout queries +function Box({ isHighlighted }: { isHighlighted: boolean }) { + const ref = useRef(null) + + useEffect(() => { + if (ref.current && isHighlighted) { + ref.current.style.width = '100px' + const width = ref.current.offsetWidth // Forces layout + ref.current.style.height = '200px' + } + }, [isHighlighted]) + + return
Content
+} + +// Correct: toggle class +function Box({ isHighlighted }: { isHighlighted: boolean }) { + return ( +
+ Content +
+ ) +} +``` + +Prefer CSS classes over inline styles when possible. CSS files are cached by the browser, and classes provide better separation of concerns and are easier to maintain. + +See [this gist](https://gist.github.com/paulirish/5d52fb081b3570c81e3a) and [CSS Triggers](https://csstriggers.com/) for more information on layout-forcing operations. diff --git a/.ai/references/vercel-react-best-practices/rules/js-cache-function-results.md b/.ai/references/vercel-react-best-practices/rules/js-cache-function-results.md new file mode 100644 index 00000000..74eb1cef --- /dev/null +++ b/.ai/references/vercel-react-best-practices/rules/js-cache-function-results.md @@ -0,0 +1,88 @@ +--- +title: Cache Repeated Function Calls +impact: MEDIUM +impactDescription: avoid redundant computation +tags: javascript, cache, memoization, performance +--- + +## Cache Repeated Function Calls + +Use a module-level Map to cache the results of a pure function that is called repeatedly with the same inputs during render. Cache only results that depend solely on the arguments, and bound the cache: a module-level Map lives as long as the page or server process, so unbounded inputs make it grow forever. Never cache user- or request-specific results in module scope on a server. + +**Incorrect (redundant computation):** + +```typescript +function ProjectList({ projects }: { projects: Project[] }) { + return ( +
+ {projects.map(project => { + // slugify() called 100+ times for same project names + const slug = slugify(project.name) + + return + })} +
+ ) +} +``` + +**Correct (cached results):** + +```typescript +// Module-level cache for a pure function, bounded by size +const MAX_SLUGS = 1000 +const slugifyCache = new Map() + +function cachedSlugify(text: string): string { + const cached = slugifyCache.get(text) + if (cached !== undefined) { + return cached + } + const result = slugify(text) + if (slugifyCache.size >= MAX_SLUGS) { + // Maps keep insertion order, so this evicts the oldest entry + slugifyCache.delete(slugifyCache.keys().next().value!) + } + slugifyCache.set(text, result) + return result +} + +function ProjectList({ projects }: { projects: Project[] }) { + return ( +
+ {projects.map(project => { + // Computed only once per unique project name + const slug = cachedSlugify(project.name) + + return + })} +
+ ) +} +``` + +**Single-value cache with explicit invalidation:** + +This result depends on browser state, not arguments, so it is correct only if every change to that state calls the invalidation function. If you cannot guarantee that, recompute instead. + +```typescript +let isLoggedInCache: boolean | null = null + +function isLoggedIn(): boolean { + if (isLoggedInCache !== null) { + return isLoggedInCache + } + + isLoggedInCache = document.cookie.includes('auth=') + return isLoggedInCache +} + +// Clear cache when auth changes +function onAuthChange() { + isLoggedInCache = null +} +``` + +Use a Map (not a hook) so it works everywhere: utilities, event handlers, not just React components. + +Reference: [How we made the Vercel Dashboard twice as fast](https://vercel.com/blog/how-we-made-the-vercel-dashboard-twice-as-fast) diff --git a/.ai/references/vercel-react-best-practices/rules/js-cache-property-access.md b/.ai/references/vercel-react-best-practices/rules/js-cache-property-access.md new file mode 100644 index 00000000..39eec906 --- /dev/null +++ b/.ai/references/vercel-react-best-practices/rules/js-cache-property-access.md @@ -0,0 +1,28 @@ +--- +title: Cache Property Access in Loops +impact: LOW-MEDIUM +impactDescription: reduces lookups +tags: javascript, loops, optimization, caching +--- + +## Cache Property Access in Loops + +Cache object property lookups in hot paths. + +**Incorrect (3 lookups × N iterations):** + +```typescript +for (let i = 0; i < arr.length; i++) { + process(obj.config.settings.value) +} +``` + +**Correct (1 lookup total):** + +```typescript +const value = obj.config.settings.value +const len = arr.length +for (let i = 0; i < len; i++) { + process(value) +} +``` diff --git a/.ai/references/vercel-react-best-practices/rules/js-cache-storage.md b/.ai/references/vercel-react-best-practices/rules/js-cache-storage.md new file mode 100644 index 00000000..4e898d81 --- /dev/null +++ b/.ai/references/vercel-react-best-practices/rules/js-cache-storage.md @@ -0,0 +1,86 @@ +--- +title: Cache Storage API Calls +impact: LOW-MEDIUM +impactDescription: reduces expensive I/O +tags: javascript, localStorage, storage, caching, performance +--- + +## Cache Storage API Calls + +`localStorage`, `sessionStorage`, and `document.cookie` are synchronous and expensive. Cache reads in memory. + +**Incorrect (reads storage on every call):** + +```typescript +function getTheme() { + return localStorage.getItem('theme') ?? 'light' +} +// Called 10 times = 10 storage reads +``` + +**Correct (Map cache):** + +```typescript +const storageCache = new Map() + +function getLocalStorage(key: string) { + if (!storageCache.has(key)) { + storageCache.set(key, localStorage.getItem(key)) + } + return storageCache.get(key) +} + +function setLocalStorage(key: string, value: string) { + localStorage.setItem(key, value) + storageCache.set(key, value) // keep cache in sync +} +``` + +Use a Map (not a hook) so it works everywhere: utilities, event handlers, not just React components. + +**Cookie caching:** + +```typescript +let cookieCache: Record | null = null + +function getCookie(name: string) { + if (!cookieCache) { + cookieCache = Object.fromEntries( + document.cookie + .split('; ') + .filter(Boolean) + // Split on the first "=" only; cookie values may contain "=" + .map(c => { + const i = c.indexOf('=') + return i < 0 ? ['', c] : [c.slice(0, i), c.slice(i + 1)] + }) + ) + } + return cookieCache[name] +} + +function setCookie(cookie: string) { + document.cookie = cookie + cookieCache = null // re-read on next access +} +``` + +**Important (invalidate on external changes):** + +If storage can change outside this code (another tab, the server), invalidate both caches: + +```typescript +window.addEventListener('storage', (e) => { + if (e.key) storageCache.delete(e.key) + else storageCache.clear() // storage.clear() in another tab +}) + +document.addEventListener('visibilitychange', () => { + if (document.visibilityState === 'visible') { + storageCache.clear() + cookieCache = null + } +}) +``` + +The `storage` event fires only for `localStorage`/`sessionStorage` changes made by other documents; it never fires for cookies. A cookie set by a server response (`Set-Cookie`) or by other code changes with no event at all, so cache a cookie only when your own code is its sole writer, and reset `cookieCache` after any request that can set it. Otherwise read `document.cookie` directly. diff --git a/.ai/references/vercel-react-best-practices/rules/js-combine-iterations.md b/.ai/references/vercel-react-best-practices/rules/js-combine-iterations.md new file mode 100644 index 00000000..044d017e --- /dev/null +++ b/.ai/references/vercel-react-best-practices/rules/js-combine-iterations.md @@ -0,0 +1,32 @@ +--- +title: Combine Multiple Array Iterations +impact: LOW-MEDIUM +impactDescription: reduces iterations +tags: javascript, arrays, loops, performance +--- + +## Combine Multiple Array Iterations + +Multiple `.filter()` or `.map()` calls iterate the array multiple times. Combine into one loop. + +**Incorrect (3 iterations):** + +```typescript +const admins = users.filter(u => u.isAdmin) +const testers = users.filter(u => u.isTester) +const inactive = users.filter(u => !u.isActive) +``` + +**Correct (1 iteration):** + +```typescript +const admins: User[] = [] +const testers: User[] = [] +const inactive: User[] = [] + +for (const user of users) { + if (user.isAdmin) admins.push(user) + if (user.isTester) testers.push(user) + if (!user.isActive) inactive.push(user) +} +``` diff --git a/.ai/references/vercel-react-best-practices/rules/js-early-exit.md b/.ai/references/vercel-react-best-practices/rules/js-early-exit.md new file mode 100644 index 00000000..44a8c58c --- /dev/null +++ b/.ai/references/vercel-react-best-practices/rules/js-early-exit.md @@ -0,0 +1,50 @@ +--- +title: Early Return from Functions +impact: LOW-MEDIUM +impactDescription: avoids unnecessary computation +tags: javascript, functions, optimization, early-return +--- + +## Early Return from Functions + +Return early when result is determined to skip unnecessary processing. + +**Incorrect (processes all items even after finding answer):** + +```typescript +function validateUsers(users: User[]) { + let hasError = false + let errorMessage = '' + + for (const user of users) { + if (!user.email) { + hasError = true + errorMessage = 'Email required' + } + if (!user.name) { + hasError = true + errorMessage = 'Name required' + } + // Continues checking all users even after error found + } + + return hasError ? { valid: false, error: errorMessage } : { valid: true } +} +``` + +**Correct (returns immediately on first error):** + +```typescript +function validateUsers(users: User[]) { + for (const user of users) { + if (!user.email) { + return { valid: false, error: 'Email required' } + } + if (!user.name) { + return { valid: false, error: 'Name required' } + } + } + + return { valid: true } +} +``` diff --git a/.ai/references/vercel-react-best-practices/rules/js-flatmap-filter.md b/.ai/references/vercel-react-best-practices/rules/js-flatmap-filter.md new file mode 100644 index 00000000..ee0edf0d --- /dev/null +++ b/.ai/references/vercel-react-best-practices/rules/js-flatmap-filter.md @@ -0,0 +1,60 @@ +--- +title: Use flatMap to Map and Filter in One Pass +impact: LOW-MEDIUM +impactDescription: eliminates intermediate array +tags: javascript, arrays, flatMap, filter, performance +--- + +## Use flatMap to Map and Filter in One Pass + +**Impact: LOW-MEDIUM (eliminates intermediate array)** + +Chaining `.map().filter(Boolean)` creates an intermediate array and iterates twice. Use `.flatMap()` to transform and filter in a single pass. + +**Incorrect (2 iterations, intermediate array):** + +```typescript +const userNames = users + .map(user => user.isActive ? user.name : null) + .filter(Boolean) +``` + +**Correct (1 iteration, no intermediate array):** + +```typescript +const userNames = users.flatMap(user => + user.isActive ? [user.name] : [] +) +``` + +**More examples:** + +```typescript +// Extract valid emails from responses +// Before +const emails = responses + .map(r => r.success ? r.data.email : null) + .filter(Boolean) + +// After +const emails = responses.flatMap(r => + r.success ? [r.data.email] : [] +) + +// Parse and filter valid numbers +// Before +const numbers = strings + .map(s => parseInt(s, 10)) + .filter(n => !isNaN(n)) + +// After +const numbers = strings.flatMap(s => { + const n = parseInt(s, 10) + return isNaN(n) ? [] : [n] +}) +``` + +**When to use:** +- Transforming items while filtering some out +- Conditional mapping where some inputs produce no output +- Parsing/validating where invalid inputs should be skipped diff --git a/.ai/references/vercel-react-best-practices/rules/js-hoist-regexp.md b/.ai/references/vercel-react-best-practices/rules/js-hoist-regexp.md new file mode 100644 index 00000000..dae3fefd --- /dev/null +++ b/.ai/references/vercel-react-best-practices/rules/js-hoist-regexp.md @@ -0,0 +1,45 @@ +--- +title: Hoist RegExp Creation +impact: LOW-MEDIUM +impactDescription: avoids recreation +tags: javascript, regexp, optimization, memoization +--- + +## Hoist RegExp Creation + +Don't create RegExp inside render. Hoist to module scope or memoize with `useMemo()`. + +**Incorrect (new RegExp every render):** + +```tsx +function Highlighter({ text, query }: Props) { + const regex = new RegExp(`(${query})`, 'gi') + const parts = text.split(regex) + return <>{parts.map((part, i) => ...)} +} +``` + +**Correct (memoize or hoist):** + +```tsx +const EMAIL_REGEX = /^[^\s@]+@[^\s@]+\.[^\s@]+$/ + +function Highlighter({ text, query }: Props) { + const regex = useMemo( + () => new RegExp(`(${escapeRegex(query)})`, 'gi'), + [query] + ) + const parts = text.split(regex) + return <>{parts.map((part, i) => ...)} +} +``` + +**Warning (global regex has mutable state):** + +Global regex (`/g`) has mutable `lastIndex` state: + +```typescript +const regex = /foo/g +regex.test('foo') // true, lastIndex = 3 +regex.test('foo') // false, lastIndex = 0 +``` diff --git a/.ai/references/vercel-react-best-practices/rules/js-index-maps.md b/.ai/references/vercel-react-best-practices/rules/js-index-maps.md new file mode 100644 index 00000000..9d357a00 --- /dev/null +++ b/.ai/references/vercel-react-best-practices/rules/js-index-maps.md @@ -0,0 +1,37 @@ +--- +title: Build Index Maps for Repeated Lookups +impact: LOW-MEDIUM +impactDescription: 1M ops to 2K ops +tags: javascript, map, indexing, optimization, performance +--- + +## Build Index Maps for Repeated Lookups + +Multiple `.find()` calls by the same key should use a Map. + +**Incorrect (O(n) per lookup):** + +```typescript +function processOrders(orders: Order[], users: User[]) { + return orders.map(order => ({ + ...order, + user: users.find(u => u.id === order.userId) + })) +} +``` + +**Correct (O(1) per lookup):** + +```typescript +function processOrders(orders: Order[], users: User[]) { + const userById = new Map(users.map(u => [u.id, u])) + + return orders.map(order => ({ + ...order, + user: userById.get(order.userId) + })) +} +``` + +Build map once (O(n)), then all lookups are O(1). +For 1000 orders × 1000 users: 1M ops → 2K ops. diff --git a/.ai/references/vercel-react-best-practices/rules/js-length-check-first.md b/.ai/references/vercel-react-best-practices/rules/js-length-check-first.md new file mode 100644 index 00000000..8b895736 --- /dev/null +++ b/.ai/references/vercel-react-best-practices/rules/js-length-check-first.md @@ -0,0 +1,49 @@ +--- +title: Early Length Check for Array Comparisons +impact: MEDIUM-HIGH +impactDescription: avoids expensive operations when lengths differ +tags: javascript, arrays, performance, optimization, comparison +--- + +## Early Length Check for Array Comparisons + +When comparing arrays with expensive operations (sorting, deep equality, serialization), check lengths first. If lengths differ, the arrays cannot be equal. + +In real-world applications, this optimization is especially valuable when the comparison runs in hot paths (event handlers, render loops). + +**Incorrect (always runs expensive comparison):** + +```typescript +function hasChanges(current: string[], original: string[]) { + // Always sorts and joins, even when lengths differ + return current.sort().join() !== original.sort().join() +} +``` + +Two O(n log n) sorts run even when `current.length` is 5 and `original.length` is 100. There is also overhead of joining the arrays and comparing the strings. + +**Correct (O(1) length check first):** + +```typescript +function hasChanges(current: string[], original: string[]) { + // Early return if lengths differ + if (current.length !== original.length) { + return true + } + // Only sort when lengths match + const currentSorted = current.toSorted() + const originalSorted = original.toSorted() + for (let i = 0; i < currentSorted.length; i++) { + if (currentSorted[i] !== originalSorted[i]) { + return true + } + } + return false +} +``` + +This new approach is more efficient because: +- It avoids the overhead of sorting and joining the arrays when lengths differ +- It avoids consuming memory for the joined strings (especially important for large arrays) +- It avoids mutating the original arrays +- It returns early when a difference is found diff --git a/.ai/references/vercel-react-best-practices/rules/js-min-max-loop.md b/.ai/references/vercel-react-best-practices/rules/js-min-max-loop.md new file mode 100644 index 00000000..60029866 --- /dev/null +++ b/.ai/references/vercel-react-best-practices/rules/js-min-max-loop.md @@ -0,0 +1,82 @@ +--- +title: Use Loop for Min/Max Instead of Sort +impact: LOW +impactDescription: O(n) instead of O(n log n) +tags: javascript, arrays, performance, sorting, algorithms +--- + +## Use Loop for Min/Max Instead of Sort + +Finding the smallest or largest element only requires a single pass through the array. Sorting is wasteful and slower. + +**Incorrect (O(n log n) - sort to find latest):** + +```typescript +interface Project { + id: string + name: string + updatedAt: number +} + +function getLatestProject(projects: Project[]) { + const sorted = [...projects].sort((a, b) => b.updatedAt - a.updatedAt) + return sorted[0] +} +``` + +Sorts the entire array just to find the maximum value. + +**Incorrect (O(n log n) - sort for oldest and newest):** + +```typescript +function getOldestAndNewest(projects: Project[]) { + const sorted = [...projects].sort((a, b) => a.updatedAt - b.updatedAt) + return { oldest: sorted[0], newest: sorted[sorted.length - 1] } +} +``` + +Still sorts unnecessarily when only min/max are needed. + +**Correct (O(n) - single loop):** + +```typescript +function getLatestProject(projects: Project[]) { + if (projects.length === 0) return null + + let latest = projects[0] + + for (let i = 1; i < projects.length; i++) { + if (projects[i].updatedAt > latest.updatedAt) { + latest = projects[i] + } + } + + return latest +} + +function getOldestAndNewest(projects: Project[]) { + if (projects.length === 0) return { oldest: null, newest: null } + + let oldest = projects[0] + let newest = projects[0] + + for (let i = 1; i < projects.length; i++) { + if (projects[i].updatedAt < oldest.updatedAt) oldest = projects[i] + if (projects[i].updatedAt > newest.updatedAt) newest = projects[i] + } + + return { oldest, newest } +} +``` + +Single pass through the array, no copying, no sorting. + +**Alternative (Math.min/Math.max for small arrays):** + +```typescript +const numbers = [5, 2, 8, 1, 9] +const min = Math.min(...numbers) +const max = Math.max(...numbers) +``` + +This works for small arrays, but can be slower or just throw an error for very large arrays due to spread operator limitations. Maximal array length is approximately 124000 in Chrome 143 and 638000 in Safari 18; exact numbers may vary - see [the fiddle](https://jsfiddle.net/qw1jabsx/4/). Use the loop approach for reliability. diff --git a/.ai/references/vercel-react-best-practices/rules/js-request-idle-callback.md b/.ai/references/vercel-react-best-practices/rules/js-request-idle-callback.md new file mode 100644 index 00000000..d81927e5 --- /dev/null +++ b/.ai/references/vercel-react-best-practices/rules/js-request-idle-callback.md @@ -0,0 +1,105 @@ +--- +title: Defer Non-Critical Work with requestIdleCallback +impact: MEDIUM +impactDescription: keeps UI responsive during background tasks +tags: javascript, performance, idle, scheduling, analytics +--- + +## Defer Non-Critical Work with requestIdleCallback + +**Impact: MEDIUM (keeps UI responsive during background tasks)** + +Use `requestIdleCallback()` to schedule non-critical work during browser idle periods. This keeps the main thread free for user interactions and animations, reducing jank and improving perceived performance. + +**Incorrect (blocks main thread during user interaction):** + +```typescript +function handleSearch(query: string) { + const results = searchItems(query) + setResults(results) + + // These block the main thread immediately + analytics.track('search', { query }) + saveToRecentSearches(query) + prefetchTopResults(results.slice(0, 3)) +} +``` + +**Correct (defers non-critical work to idle time):** + +```typescript +function handleSearch(query: string) { + const results = searchItems(query) + setResults(results) + + // Defer non-critical work to idle periods + requestIdleCallback(() => { + analytics.track('search', { query }) + }) + + requestIdleCallback(() => { + saveToRecentSearches(query) + }) + + requestIdleCallback(() => { + prefetchTopResults(results.slice(0, 3)) + }) +} +``` + +**With timeout for required work:** + +```typescript +// Ensure analytics fires within 2 seconds even if browser stays busy +requestIdleCallback( + () => analytics.track('page_view', { path: location.pathname }), + { timeout: 2000 } +) +``` + +**Chunking large tasks:** + +```typescript +function processLargeDataset(items: Item[]) { + let index = 0 + + function processChunk(deadline: IdleDeadline) { + // Process items while we have idle time (aim for <50ms chunks) + while (index < items.length && deadline.timeRemaining() > 0) { + processItem(items[index]) + index++ + } + + // Schedule next chunk if more items remain + if (index < items.length) { + requestIdleCallback(processChunk) + } + } + + requestIdleCallback(processChunk) +} +``` + +**With fallback for unsupported browsers:** + +```typescript +const scheduleIdleWork = window.requestIdleCallback ?? ((cb: () => void) => setTimeout(cb, 1)) + +scheduleIdleWork(() => { + // Non-critical work +}) +``` + +**When to use:** + +- Analytics and telemetry +- Saving state to localStorage/IndexedDB +- Prefetching resources for likely next actions +- Processing non-urgent data transformations +- Lazy initialization of non-critical features + +**When NOT to use:** + +- User-initiated actions that need immediate feedback +- Rendering updates the user is waiting for +- Time-sensitive operations diff --git a/.ai/references/vercel-react-best-practices/rules/js-set-map-lookups.md b/.ai/references/vercel-react-best-practices/rules/js-set-map-lookups.md new file mode 100644 index 00000000..680a4892 --- /dev/null +++ b/.ai/references/vercel-react-best-practices/rules/js-set-map-lookups.md @@ -0,0 +1,24 @@ +--- +title: Use Set/Map for O(1) Lookups +impact: LOW-MEDIUM +impactDescription: O(n) to O(1) +tags: javascript, set, map, data-structures, performance +--- + +## Use Set/Map for O(1) Lookups + +Convert arrays to Set/Map for repeated membership checks. + +**Incorrect (O(n) per check):** + +```typescript +const allowedIds = ['a', 'b', 'c', ...] +items.filter(item => allowedIds.includes(item.id)) +``` + +**Correct (O(1) per check):** + +```typescript +const allowedIds = new Set(['a', 'b', 'c', ...]) +items.filter(item => allowedIds.has(item.id)) +``` diff --git a/.ai/references/vercel-react-best-practices/rules/js-tosorted-immutable.md b/.ai/references/vercel-react-best-practices/rules/js-tosorted-immutable.md new file mode 100644 index 00000000..eae8b3f8 --- /dev/null +++ b/.ai/references/vercel-react-best-practices/rules/js-tosorted-immutable.md @@ -0,0 +1,57 @@ +--- +title: Use toSorted() Instead of sort() for Immutability +impact: MEDIUM-HIGH +impactDescription: prevents mutation bugs in React state +tags: javascript, arrays, immutability, react, state, mutation +--- + +## Use toSorted() Instead of sort() for Immutability + +`.sort()` mutates the array in place, which can cause bugs with React state and props. Use `.toSorted()` to create a new sorted array without mutation. + +**Incorrect (mutates original array):** + +```typescript +function UserList({ users }: { users: User[] }) { + // Mutates the users prop array! + const sorted = useMemo( + () => users.sort((a, b) => a.name.localeCompare(b.name)), + [users] + ) + return
{sorted.map(renderUser)}
+} +``` + +**Correct (creates new array):** + +```typescript +function UserList({ users }: { users: User[] }) { + // Creates new sorted array, original unchanged + const sorted = useMemo( + () => users.toSorted((a, b) => a.name.localeCompare(b.name)), + [users] + ) + return
{sorted.map(renderUser)}
+} +``` + +**Why this matters in React:** + +1. Props/state mutations break React's immutability model - React expects props and state to be treated as read-only +2. Causes stale closure bugs - Mutating arrays inside closures (callbacks, effects) can lead to unexpected behavior + +**Browser support (fallback for older browsers):** + +`.toSorted()` is available in all modern browsers (Chrome 110+, Safari 16+, Firefox 115+, Node.js 20+). For older environments, use spread operator: + +```typescript +// Fallback for older browsers +const sorted = [...items].sort((a, b) => a.value - b.value) +``` + +**Other immutable array methods:** + +- `.toSorted()` - immutable sort +- `.toReversed()` - immutable reverse +- `.toSpliced()` - immutable splice +- `.with()` - immutable element replacement diff --git a/.ai/references/vercel-react-best-practices/rules/rendering-activity.md b/.ai/references/vercel-react-best-practices/rules/rendering-activity.md new file mode 100644 index 00000000..c957a490 --- /dev/null +++ b/.ai/references/vercel-react-best-practices/rules/rendering-activity.md @@ -0,0 +1,26 @@ +--- +title: Use Activity Component for Show/Hide +impact: MEDIUM +impactDescription: preserves state/DOM +tags: rendering, activity, visibility, state-preservation +--- + +## Use Activity Component for Show/Hide + +Use React's `` to preserve state/DOM for expensive components that frequently toggle visibility. + +**Usage:** + +```tsx +import { Activity } from 'react' + +function Dropdown({ isOpen }: Props) { + return ( + + + + ) +} +``` + +Avoids expensive re-renders and state loss. diff --git a/.ai/references/vercel-react-best-practices/rules/rendering-animate-svg-wrapper.md b/.ai/references/vercel-react-best-practices/rules/rendering-animate-svg-wrapper.md new file mode 100644 index 00000000..1fcba409 --- /dev/null +++ b/.ai/references/vercel-react-best-practices/rules/rendering-animate-svg-wrapper.md @@ -0,0 +1,47 @@ +--- +title: Animate SVG Wrapper Instead of SVG Element +impact: LOW +impactDescription: enables hardware acceleration +tags: rendering, svg, css, animation, performance +--- + +## Animate SVG Wrapper Instead of SVG Element + +Many browsers don't have hardware acceleration for CSS3 animations on SVG elements. Wrap SVG in a `
` and animate the wrapper instead. + +**Incorrect (animating SVG directly - no hardware acceleration):** + +```tsx +function LoadingSpinner() { + return ( + + + + ) +} +``` + +**Correct (animating wrapper div - hardware accelerated):** + +```tsx +function LoadingSpinner() { + return ( +
+ + + +
+ ) +} +``` + +This applies to all CSS transforms and transitions (`transform`, `opacity`, `translate`, `scale`, `rotate`). The wrapper div allows browsers to use GPU acceleration for smoother animations. diff --git a/.ai/references/vercel-react-best-practices/rules/rendering-conditional-render.md b/.ai/references/vercel-react-best-practices/rules/rendering-conditional-render.md new file mode 100644 index 00000000..7e866f58 --- /dev/null +++ b/.ai/references/vercel-react-best-practices/rules/rendering-conditional-render.md @@ -0,0 +1,40 @@ +--- +title: Use Explicit Conditional Rendering +impact: LOW +impactDescription: prevents rendering 0 or NaN +tags: rendering, conditional, jsx, falsy-values +--- + +## Use Explicit Conditional Rendering + +Use explicit ternary operators (`? :`) instead of `&&` for conditional rendering when the condition can be `0`, `NaN`, or other falsy values that render. + +**Incorrect (renders "0" when count is 0):** + +```tsx +function Badge({ count }: { count: number }) { + return ( +
+ {count && {count}} +
+ ) +} + +// When count = 0, renders:
0
+// When count = 5, renders:
5
+``` + +**Correct (renders nothing when count is 0):** + +```tsx +function Badge({ count }: { count: number }) { + return ( +
+ {count > 0 ? {count} : null} +
+ ) +} + +// When count = 0, renders:
+// When count = 5, renders:
5
+``` diff --git a/.ai/references/vercel-react-best-practices/rules/rendering-content-visibility.md b/.ai/references/vercel-react-best-practices/rules/rendering-content-visibility.md new file mode 100644 index 00000000..aa665636 --- /dev/null +++ b/.ai/references/vercel-react-best-practices/rules/rendering-content-visibility.md @@ -0,0 +1,38 @@ +--- +title: CSS content-visibility for Long Lists +impact: HIGH +impactDescription: faster initial render +tags: rendering, css, content-visibility, long-lists +--- + +## CSS content-visibility for Long Lists + +Apply `content-visibility: auto` to defer off-screen rendering. + +**CSS:** + +```css +.message-item { + content-visibility: auto; + contain-intrinsic-size: 0 80px; +} +``` + +**Example:** + +```tsx +function MessageList({ messages }: { messages: Message[] }) { + return ( +
+ {messages.map(msg => ( +
+ +
{msg.content}
+
+ ))} +
+ ) +} +``` + +For 1000 messages, browser skips layout/paint for ~990 off-screen items (10× faster initial render). diff --git a/.ai/references/vercel-react-best-practices/rules/rendering-hoist-jsx.md b/.ai/references/vercel-react-best-practices/rules/rendering-hoist-jsx.md new file mode 100644 index 00000000..32d2f3fc --- /dev/null +++ b/.ai/references/vercel-react-best-practices/rules/rendering-hoist-jsx.md @@ -0,0 +1,46 @@ +--- +title: Hoist Static JSX Elements +impact: LOW +impactDescription: avoids re-creation +tags: rendering, jsx, static, optimization +--- + +## Hoist Static JSX Elements + +Extract static JSX outside components to avoid re-creation. + +**Incorrect (recreates element every render):** + +```tsx +function LoadingSkeleton() { + return
+} + +function Container() { + return ( +
+ {loading && } +
+ ) +} +``` + +**Correct (reuses same element):** + +```tsx +const loadingSkeleton = ( +
+) + +function Container() { + return ( +
+ {loading && loadingSkeleton} +
+ ) +} +``` + +This is especially helpful for large and static SVG nodes, which can be expensive to recreate on every render. + +**Note:** If your project has [React Compiler](https://react.dev/learn/react-compiler) enabled, the compiler automatically hoists static JSX elements and optimizes component re-renders, making manual hoisting unnecessary. diff --git a/.ai/references/vercel-react-best-practices/rules/rendering-hydration-no-flicker.md b/.ai/references/vercel-react-best-practices/rules/rendering-hydration-no-flicker.md new file mode 100644 index 00000000..340cdd4e --- /dev/null +++ b/.ai/references/vercel-react-best-practices/rules/rendering-hydration-no-flicker.md @@ -0,0 +1,82 @@ +--- +title: Render Client-Stored Values Without Flickering +impact: MEDIUM +impactDescription: avoids visual flicker and unexpected hydration warnings +tags: rendering, ssr, hydration, localStorage, flicker +--- + +## Render Client-Stored Values Without Flickering + +When rendering content that depends on client-side storage (localStorage, cookies), avoid both SSR breakage and post-hydration flickering by injecting a synchronous script that updates the DOM before React hydrates. + +**Incorrect (breaks SSR):** + +```tsx +function ThemeWrapper({ children }: { children: ReactNode }) { + // localStorage is not available on server - throws error + const theme = localStorage.getItem('theme') || 'light' + + return ( +
+ {children} +
+ ) +} +``` + +Server-side rendering will fail because `localStorage` is undefined. + +**Incorrect (visual flickering):** + +```tsx +function ThemeWrapper({ children }: { children: ReactNode }) { + const [theme, setTheme] = useState('light') + + useEffect(() => { + // Runs after hydration - causes visible flash + const stored = localStorage.getItem('theme') + if (stored) { + setTheme(stored) + } + }, []) + + return ( +
+ {children} +
+ ) +} +``` + +Component first renders with default value (`light`), then updates after hydration, causing a visible flash of incorrect content. + +**Correct (no flicker; the expected mismatch is marked as intentional):** + +```tsx +function ThemeWrapper({ children }: { children: ReactNode }) { + return ( + <> +
+ {children} +
+