diff --git a/optional-skills/web-development/react-best-practices/SKILL.md b/optional-skills/web-development/react-best-practices/SKILL.md new file mode 100644 index 00000000000..9e6c7ede0f9 --- /dev/null +++ b/optional-skills/web-development/react-best-practices/SKILL.md @@ -0,0 +1,85 @@ +--- +name: react-best-practices +description: React/Next.js performance rules from Vercel Engineering. +version: 0.1.0 +author: Vercel (vercel-labs), Hermes Agent +license: MIT +platforms: [linux, macos, windows] +metadata: + hermes: + tags: [React, NextJS, Performance, Frontend] + related_skills: [] +--- + +# React Best Practices + +Performance optimization guidance for React and Next.js applications, originating from Vercel Engineering's `react-best-practices` agent skill (vercel-labs/agent-skills, MIT). It contains 70 rules across 8 categories, prioritized by impact — from critical (eliminating waterfalls, bundle size) down to incremental micro-optimizations. Upstream rule IDs are preserved verbatim for traceability. + +## When to Use + +- Writing new React components or Next.js pages/routes +- Implementing data fetching (client- or server-side, RSC, API routes, server actions) +- Reviewing or refactoring React/Next.js code for performance +- Optimizing bundle size, load times, or interaction responsiveness + +## Rule Categories by Priority + +Work top-down: a fixed waterfall or a smaller bundle dwarfs any memoization win. + +| Priority | Category | Impact | Rule prefix | Reference file | +|----------|----------|--------|-------------|----------------| +| 1 | Eliminating Waterfalls | CRITICAL | `async-` | `references/async-waterfalls.md` | +| 2 | Bundle Size Optimization | CRITICAL | `bundle-` | `references/bundle-optimization.md` | +| 3 | Server-Side Performance | HIGH | `server-` | `references/server-side.md` | +| 4 | Client-Side Data Fetching | MEDIUM-HIGH | `client-` | `references/client-data-fetching.md` | +| 5 | Re-render Optimization | MEDIUM | `rerender-` | `references/rerender-optimization.md` | +| 6 | Rendering Performance | MEDIUM | `rendering-` | `references/rendering-performance.md` | +| 7 | JavaScript Performance | LOW-MEDIUM | `js-` | `references/js-performance.md` | +| 8 | Advanced Patterns | LOW | `advanced-` | `references/advanced-patterns.md` | + +Each reference file contains the full upstream rules for that category: rationale, incorrect vs. correct code, and impact estimates. Load only the categories relevant to the code at hand with `skill_view(name='react-best-practices', file_path='references/.md')`. + +## Core Rules at a Glance + +The highest-leverage rules, by category (full detail in the reference files): + +**Waterfalls (`references/async-waterfalls.md`)** — `async-parallel`: use `Promise.all()` for independent awaits. `async-defer-await`: move `await` into the branch that uses it. `async-cheap-condition-before-await`: check cheap sync conditions before awaiting. `async-api-routes`: start promises early, await late. `async-suspense-boundaries`: stream with Suspense instead of blocking the whole page. `async-dependencies`: use `better-all` for partially dependent tasks. + +**Bundle (`references/bundle-optimization.md`)** — `bundle-barrel-imports`: import directly, never through barrel files. `bundle-dynamic-imports`: `next/dynamic` for heavy components. `bundle-defer-third-party`: load analytics after hydration. `bundle-conditional` and `bundle-preload`: load on activation, preload on hover/focus. `bundle-analyzable-paths`: keep import paths statically analyzable. + +**Server (`references/server-side.md`)** — `server-cache-react`: use React `cache()` for per-request dedup. `server-cache-lru`: LRU cache across requests. `server-parallel-fetching` / `server-parallel-nested-fetching`: restructure components so fetches run concurrently. `server-hoist-static-io`: hoist static I/O to module level. `server-after-nonblocking`: use `after()` for non-blocking work. `server-auth-actions`: authenticate server actions like API routes. `server-serialization` / `server-dedup-props`: minimize and dedupe RSC prop payloads. `server-no-shared-module-state`: no module-level mutable request state. + +**Client fetching (`references/client-data-fetching.md`)** — `client-swr-dedup`: SWR for automatic dedup. `client-event-listeners` / `client-passive-event-listeners`: dedupe global listeners, passive for scroll. `client-localstorage-schema`: version and minimize localStorage data. + +**Re-renders (`references/rerender-optimization.md`)** — `rerender-derived-state-no-effect`: derive state during render, never via `useEffect` + `setState`. `rerender-functional-setstate`: functional updates for stable callbacks. `rerender-lazy-state-init`: pass a function to `useState` for expensive init. `rerender-no-inline-components`: never define components inside components. `rerender-memo`, `rerender-defer-reads`, `rerender-transitions`, `rerender-use-deferred-value`, `rerender-use-ref-transient-values`, and more. + +**Rendering (`references/rendering-performance.md`)** — `rendering-content-visibility`, `rendering-hoist-jsx`, `rendering-conditional-render` (ternary, not `&&`), `rendering-hydration-no-flicker`, `rendering-resource-hints`, `rendering-usetransition-loading`, and more. + +**JS micro-perf (`references/js-performance.md`)** — `js-set-map-lookups`, `js-index-maps`, `js-combine-iterations`, `js-early-exit`, `js-hoist-regexp`, `js-tosorted-immutable`, `js-request-idle-callback`, and more — for hot paths only. + +**Advanced (`references/advanced-patterns.md`)** — `advanced-use-latest`, `advanced-event-handler-refs`, `advanced-init-once`, `advanced-effect-event-deps`. + +## Applying the Rules with Hermes Tools + +- Inspect code with `read_file` and locate suspect patterns with `search_files` — e.g. `search_files(pattern='await .*\n.*await', target='content', file_glob='*.tsx')` for sequential awaits, or `pattern='useEffect'` to audit effects for derived-state misuse. +- Apply fixes with `patch` (targeted find-and-replace), citing the rule ID in your explanation so reviewers can trace the rationale. +- Never use grep/cat/sed via terminal for this — `search_files`/`read_file`/`patch` are the correct tools. + +## Pitfalls + +- **Don't memoize first.** `useMemo`/`memo` on simple expressions adds overhead (`rerender-simple-expression-in-memo`); fix waterfalls and bundle size before re-render tuning. +- **`useEffect` for derived state is a bug, not a style choice** — it causes a double render and tearing (`rerender-derived-state-no-effect`). +- **Parallelizing dependent operations breaks correctness.** Only `Promise.all()` genuinely independent work; use `better-all` or restructuring for partial dependencies (`async-dependencies`). +- **Dynamic imports of tiny modules hurt** — the request overhead exceeds the saved bytes. Reserve `next/dynamic` for genuinely heavy components. +- **JS micro-optimizations (category 7) only matter in hot paths** — don't churn cold code for them during review. +- Rules assume modern React (18/19) and Next.js App Router; some (e.g. `rendering-activity`, `after()`) need recent versions — check the project's dependencies first. + +## Applying During Code Review + +1. Scan for sequential awaits, fetch-in-loop, and blocking data fetches → category 1 (CRITICAL). +2. Check imports: barrel files, heavy libs in initial bundle, eager third-party scripts → category 2 (CRITICAL). +3. Server code: missing `cache()`, serial component fetches, unauthenticated server actions, oversized RSC props → category 3. +4. Client fetching without SWR/dedup; unversioned localStorage → category 4. +5. Effects that set derived state, inline component definitions, unstable deps → category 5. +6. Only then consider rendering tweaks (6), JS micro-perf in hot paths (7), and advanced patterns (8). +7. For every finding, cite the upstream rule ID and load the matching `references/*.md` for the incorrect/correct example before proposing a `patch`. diff --git a/optional-skills/web-development/react-best-practices/references/advanced-patterns.md b/optional-skills/web-development/react-best-practices/references/advanced-patterns.md new file mode 100644 index 00000000000..fb47522bbbd --- /dev/null +++ b/optional-skills/web-development/react-best-practices/references/advanced-patterns.md @@ -0,0 +1,189 @@ +# Advanced Patterns (advanced-*) + +**Impact: LOW.** Advanced patterns for specific cases that require careful implementation. + +Rules below are from Vercel's `react-best-practices` skill (MIT, vercel-labs/agent-skills). Rule IDs match upstream filenames for traceability. + +--- + +## `advanced-effect-event-deps` — Do Not Put Effect Events in Dependency Arrays + +**Impact: LOW (avoids unnecessary effect re-runs and lint errors)** + +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) + +--- + +## `advanced-event-handler-refs` — Store Event Handlers in Refs + +**Impact: LOW (stable subscriptions)** + +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: it creates a stable function reference that always calls the latest version of the handler. + +--- + +## `advanced-init-once` — Initialize App Once, Not Per Mount + +**Impact: LOW-MEDIUM (avoids duplicate init in development)** + +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) + +--- + +## `advanced-use-latest` — useEffectEvent for Stable Callback Refs + +**Impact: LOW (prevents effect re-runs)** + +Access latest values in callbacks without adding them to dependency arrays. Prevents effect re-runs while avoiding stale closures. + +**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/optional-skills/web-development/react-best-practices/references/async-waterfalls.md b/optional-skills/web-development/react-best-practices/references/async-waterfalls.md new file mode 100644 index 00000000000..81908a45c74 --- /dev/null +++ b/optional-skills/web-development/react-best-practices/references/async-waterfalls.md @@ -0,0 +1,328 @@ +# Eliminating Waterfalls (async-*) + +**Impact: CRITICAL.** Waterfalls are the #1 performance killer. Each sequential await adds full network latency. Eliminating them yields the largest gains. + +Rules below are from Vercel's `react-best-practices` skill (MIT, vercel-labs/agent-skills). Rule IDs match upstream filenames for traceability. + +--- + +## `async-api-routes` — Prevent Waterfall Chains in API Routes + +**Impact: CRITICAL (2-10× improvement)** + +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() + const session = await sessionPromise + const [config, data] = await Promise.all([ + configPromise, + fetchData(session.user.id) + ]) + return Response.json({ data, config }) +} +``` + +For operations with more complex dependency chains, use `better-all` to automatically maximize parallelism (see Dependency-Based Parallelization). + +--- + +## `async-cheap-condition-before-await` — Check Cheap Conditions Before Async Flags + +**Impact: HIGH (avoids unnecessary async work when a synchronous guard already fails)** + +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. + +--- + +## `async-defer-await` — Defer Await Until Needed + +**Impact: HIGH (avoids blocking unused code paths)** + +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). + +--- + +## `async-dependencies` — Dependency-Based Parallelization + +**Impact: CRITICAL (2-10× improvement)** + +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) + +--- + +## `async-parallel` — Promise.all() for Independent Operations + +**Impact: CRITICAL (2-10× improvement)** + +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() +]) +``` + +--- + +## `async-suspense-boundaries` — Strategic Suspense Boundaries + +**Impact: HIGH (faster initial paint)** + +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/optional-skills/web-development/react-best-practices/references/bundle-optimization.md b/optional-skills/web-development/react-best-practices/references/bundle-optimization.md new file mode 100644 index 00000000000..bbe58557810 --- /dev/null +++ b/optional-skills/web-development/react-best-practices/references/bundle-optimization.md @@ -0,0 +1,281 @@ +# Bundle Size Optimization (bundle-*) + +**Impact: CRITICAL.** Reducing initial bundle size improves Time to Interactive and Largest Contentful Paint. + +Rules below are from Vercel's `react-best-practices` skill (MIT, vercel-labs/agent-skills). Rule IDs match upstream filenames for traceability. + +--- + +## `bundle-analyzable-paths` — Prefer Statically Analyzable Paths + +**Impact: HIGH (avoids accidental broad bundles and file traces)** + +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/) + +--- + +## `bundle-barrel-imports` — Avoid Barrel File Imports + +**Impact: CRITICAL (200-800ms import cost, slow builds)** + +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) + +--- + +## `bundle-conditional` — Conditional Module Loading + +**Impact: HIGH (loads large data only when needed)** + +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 && typeof window !== 'undefined') { + import('./animation-frames.js') + .then(mod => setFrames(mod.frames)) + .catch(() => setEnabled(false)) + } + }, [enabled, frames, setEnabled]) + + if (!frames) return + return +} +``` + +The `typeof window !== 'undefined'` check prevents bundling this module for SSR, optimizing server bundle size and build speed. + +--- + +## `bundle-defer-third-party` — Defer Non-Critical Third-Party Libraries + +**Impact: MEDIUM (loads after hydration)** + +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} + + + + ) +} +``` + +--- + +## `bundle-dynamic-imports` — Dynamic Imports for Heavy Components + +**Impact: CRITICAL (directly affects TTI and LCP)** + +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 +} +``` + +--- + +## `bundle-preload` — Preload Based on User Intent + +**Impact: MEDIUM (reduces perceived latency)** + +Preload heavy bundles before they're needed to reduce perceived latency. + +**Example (preload on hover/focus):** + +```tsx +function EditorButton({ onClick }: { onClick: () => void }) { + const preload = () => { + if (typeof window !== 'undefined') { + void import('./monaco-editor') + } + } + + return ( + + ) +} +``` + +**Example (preload when feature flag is enabled):** + +```tsx +function FlagsProvider({ children, flags }: Props) { + useEffect(() => { + if (flags.editorEnabled && typeof window !== 'undefined') { + void import('./monaco-editor').then(mod => mod.init()) + } + }, [flags.editorEnabled]) + + return + {children} + +} +``` + +The `typeof window !== 'undefined'` check prevents bundling preloaded modules for SSR, optimizing server bundle size and build speed. diff --git a/optional-skills/web-development/react-best-practices/references/client-data-fetching.md b/optional-skills/web-development/react-best-practices/references/client-data-fetching.md new file mode 100644 index 00000000000..ada45f04794 --- /dev/null +++ b/optional-skills/web-development/react-best-practices/references/client-data-fetching.md @@ -0,0 +1,246 @@ +# Client-Side Data Fetching (client-*) + +**Impact: MEDIUM-HIGH.** Automatic deduplication and efficient data fetching patterns reduce redundant network requests. + +Rules below are from Vercel's `react-best-practices` skill (MIT, vercel-labs/agent-skills). Rule IDs match upstream filenames for traceability. + +--- + +## `client-event-listeners` — Deduplicate Global Event Listeners + +**Impact: LOW (single listener for N components)** + +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', () => { /* ... */ }) + // ... +} +``` + +--- + +## `client-localstorage-schema` — Version and Minimize localStorage Data + +**Impact: MEDIUM (prevents schema conflicts, reduces storage size)** + +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. + +--- + +## `client-passive-event-listeners` — Use Passive Event Listeners for Scrolling Performance + +**Impact: MEDIUM (eliminates scroll delay caused by event listeners)** + +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()`. + +--- + +## `client-swr-dedup` — Use SWR for Automatic Deduplication + +**Impact: MEDIUM-HIGH (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/optional-skills/web-development/react-best-practices/references/js-performance.md b/optional-skills/web-development/react-best-practices/references/js-performance.md new file mode 100644 index 00000000000..e2a6bc541f7 --- /dev/null +++ b/optional-skills/web-development/react-best-practices/references/js-performance.md @@ -0,0 +1,803 @@ +# JavaScript Performance (js-*) + +**Impact: LOW-MEDIUM.** Micro-optimizations for hot paths can add up to meaningful improvements. + +Rules below are from Vercel's `react-best-practices` skill (MIT, vercel-labs/agent-skills). Rule IDs match upstream filenames for traceability. + +--- + +## `js-batch-dom-css` — Avoid Layout Thrashing + +**Impact: MEDIUM (prevents forced synchronous layouts and reduces performance bottlenecks)** + +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. + +--- + +## `js-cache-function-results` — Cache Repeated Function Calls + +**Impact: MEDIUM (avoid redundant computation)** + +Use a module-level Map to cache function results when the same function is called repeatedly with the same inputs during render. + +**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 +const slugifyCache = new Map() + +function cachedSlugify(text: string): string { + if (slugifyCache.has(text)) { + return slugifyCache.get(text)! + } + const result = slugify(text) + 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 + })} +
+ ) +} +``` + +**Simpler pattern for single-value functions:** + +```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) + +--- + +## `js-cache-property-access` — Cache Property Access in Loops + +**Impact: LOW-MEDIUM (reduces lookups)** + +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) +} +``` + +--- + +## `js-cache-storage` — Cache Storage API Calls + +**Impact: LOW-MEDIUM (reduces expensive I/O)** + +`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('; ').map(c => c.split('=')) + ) + } + return cookieCache[name] +} +``` + +**Important (invalidate on external changes):** + +If storage can change externally (another tab, server-set cookies), invalidate cache: + +```typescript +window.addEventListener('storage', (e) => { + if (e.key) storageCache.delete(e.key) +}) + +document.addEventListener('visibilitychange', () => { + if (document.visibilityState === 'visible') { + storageCache.clear() + } +}) +``` + +--- + +## `js-combine-iterations` — Combine Multiple Array Iterations + +**Impact: LOW-MEDIUM (reduces 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) +} +``` + +--- + +## `js-early-exit` — Early Return from Functions + +**Impact: LOW-MEDIUM (avoids unnecessary computation)** + +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 } +} +``` + +--- + +## `js-flatmap-filter` — Use flatMap to Map and Filter in One Pass + +**Impact: LOW-MEDIUM (eliminates intermediate array)** + +**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 + +--- + +## `js-hoist-regexp` — Hoist RegExp Creation + +**Impact: LOW-MEDIUM (avoids recreation)** + +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 +``` + +--- + +## `js-index-maps` — Build Index Maps for Repeated Lookups + +**Impact: LOW-MEDIUM (1M ops to 2K ops)** + +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. + +--- + +## `js-length-check-first` — Early Length Check for Array Comparisons + +**Impact: MEDIUM-HIGH (avoids expensive operations when lengths differ)** + +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 + +--- + +## `js-min-max-loop` — Use Loop for Min/Max Instead of Sort + +**Impact: LOW (O(n) instead of O(n log n))** + +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. + +--- + +## `js-request-idle-callback` — Defer Non-Critical Work with requestIdleCallback + +**Impact: MEDIUM (keeps UI responsive during background tasks)** + +**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 + +--- + +## `js-set-map-lookups` — Use Set/Map for O(1) Lookups + +**Impact: LOW-MEDIUM (O(n) to O(1))** + +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)) +``` + +--- + +## `js-tosorted-immutable` — Use toSorted() Instead of sort() for Immutability + +**Impact: MEDIUM-HIGH (prevents mutation bugs in React state)** + +`.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/optional-skills/web-development/react-best-practices/references/rendering-performance.md b/optional-skills/web-development/react-best-practices/references/rendering-performance.md new file mode 100644 index 00000000000..ef1606802da --- /dev/null +++ b/optional-skills/web-development/react-best-practices/references/rendering-performance.md @@ -0,0 +1,548 @@ +# Rendering Performance (rendering-*) + +**Impact: MEDIUM.** Optimizing the rendering process reduces the work the browser needs to do. + +Rules below are from Vercel's `react-best-practices` skill (MIT, vercel-labs/agent-skills). Rule IDs match upstream filenames for traceability. + +--- + +## `rendering-activity` — Use Activity Component for Show/Hide + +**Impact: MEDIUM (preserves state/DOM)** + +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. + +--- + +## `rendering-animate-svg-wrapper` — Animate SVG Wrapper Instead of SVG Element + +**Impact: LOW (enables hardware acceleration)** + +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. + +--- + +## `rendering-conditional-render` — Use Explicit Conditional Rendering + +**Impact: LOW (prevents rendering 0 or NaN)** + +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
+``` + +--- + +## `rendering-content-visibility` — CSS content-visibility for Long Lists + +**Impact: HIGH (faster initial render)** + +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). + +--- + +## `rendering-hoist-jsx` — Hoist Static JSX Elements + +**Impact: LOW (avoids re-creation)** + +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. + +--- + +## `rendering-hydration-no-flicker` — Prevent Hydration Mismatch Without Flickering + +**Impact: MEDIUM (avoids visual flicker and hydration errors)** + +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, no hydration mismatch):** + +```tsx +function ThemeWrapper({ children }: { children: ReactNode }) { + return ( + <> +
+ {children} +
+