AIStoreHub Package Vault: Vercel Agent Skills
Package Slug: vercel-agent-skills
Archetype: skill
Upstream Repository: https://github.com/vercel-labs/agent-skills
Workspace Files & Specifications (69 files)
- AGENTS.md (3367 bytes)
# AGENTS.md This file provides guidance to AI coding agents (Claude Code, Cursor, Copilot, etc.) when working with code in this repository. ## Repository Overview A collection of skills for AI coding agents working with Vercel projects. Skills are packaged instructions and scripts that extend agent capabilities. ## Creating a New Skill ### Directory Structure ``` skills/ {skill-name}/ # kebab-case directory name SKILL.md # Required: skill definition scripts/ # Optional: executable scripts {script-name}.sh # Bash scripts {script-name}.mjs # Node scripts references/ # Optional: supporting docs loaded on demand lib/ # Optional: shared code for scripts ``` ### Naming Conventions - **Skill directory**: `kebab-case` (e.g., `vercel-deploy`, `log-monitor`) - **SKILL.md**: Always uppercase, always this exact filename - **Scripts**: `kebab-case.sh` or `kebab-case.mjs` (e.g., `deploy.sh`, `collect-signals.mjs`) ### SKILL.md Format ```markdown --- name: {skill-name} description: {One sentence describing when to use this skill. Include trigger phrases like "Deploy my app", "Check logs", etc.} --- # {Skill Title} {Brief description of what the skill does.} ## How It Works {Numbered list explaining the skill's workflow} ## Usage ```bash bash /mnt/skills/user/{skill-name}/scripts/{script}.sh [args] ``` **Arguments:** - `arg1` - Description (defaults to X) **Examples:** {Show 2-3 common usage patterns} ## Output {Show example output users will see} ## Present Results to User {Template for how Claude should format results when presenting to users} ## Troubleshooting {Common issues and solutions, especially network/permissions errors} ``` ### Best Practices for Context Efficiency Skills are loaded on-demand — only the skill name and description are loaded at startup. The full `SKILL.md` loads into context only when the agent decides the skill is relevant. To minimize context usage: - **Keep SKILL.md under 500 lines** — put detailed reference material in separate files - **Write specific descriptions** — helps the agent know exactly when to activate the skill - **Use progressive disclosure** — reference supporting files that get read only when needed - **Prefer scripts over inline code** — script execution doesn't consume context (only output does) - **File references work one level deep** — link directly from SKILL.md to supporting files ### Script Requirements - Bash scripts: use `#!/bin/bash` and `set -e` - Node scripts: use `#!/usr/bin/env node` and `.mjs` - Write status messages to stderr - Write machine-readable output (JSON) to stdout - Include a cleanup trap for temp files when scripts create them - Reference scripts by relative path, for example `node scripts/{script}.mjs` ### End-User Installation Document skills.sh installation for public skills: ```bash npx skills add vercel-labs/agent-skills --skill {skill-name} ``` For manual installs, document the native path when the skill needs one. **Claude Code:** ```bash cp -r skills/{skill-name} ~/.claude/skills/ ``` **claude.ai:** Add the skill to project knowledge or paste SKILL.md contents into the conversation. If the skill requires network access, instruct users to add required domains at `claude.ai/settings/capabilities`. - aistorehub.json (486 bytes)
{ "name": "Vercel Agent Skills", "slug": "vercel-agent-skills", "version": "1.0.0", "type": "skill", "description": "Official Vercel agent skills suite featuring web design guidelines, Vercel React best practices, performance budgets, and anti-slop frontend standards for modern web engineering.", "owner": "community", "repository": "catalog", "github_repo_url": "https://github.com/vercel-labs/agent-skills", "tags": [], "imported_at": "2026-11-21T23:56:36.372Z" } - CLAUDE.md (9 bytes)
AGENTS.md
- INSTRUCTIONS.md (1233 bytes)
--- name: writing-guidelines description: Review docs/prose for Writing Guidelines compliance. Use when asked to "review my docs", "check writing style", "audit prose", "review docs voice and tone", or "check this page against the writing handbook". metadata: author: vercel version: "1.0.0" argument-hint: <file-or-pattern> --- # Writing Guidelines Review files for compliance with Writing Guidelines. ## How It Works 1. Fetch the latest guidelines from the source URL below 2. Read the specified files (or prompt user for files/pattern) 3. Check against all rules in the fetched guidelines 4. Output findings in the terse `file:line` format ## Guidelines Source Fetch fresh guidelines before each review: ``` https://raw.githubusercontent.com/vercel-labs/writing-guidelines/main/command.md ``` Use WebFetch to retrieve the latest rules. The fetched content contains all the rules and output format instructions. ## Usage When a user provides a file or pattern argument: 1. Fetch guidelines from the source URL above 2. Read the specified files 3. Apply all rules from the fetched guidelines 4. Output findings using the format specified in the guidelines If no files specified, ask the user which files to review.
- README.md (1084 bytes)
# vercel-agent-skills: Modern Web & React Engineering Rules > Official Vercel agent skills suite featuring web design guidelines, Vercel React best practices, and anti-slop frontend standards. **Ecosystem Registry:** [skills.sh](https://skills.sh) **Source Repository:** [vercel-labs/agent-skills](https://github.com/vercel-labs/agent-skills) ## Included Agent Skills 1. **`web-design-guidelines`**: Teaches coding agents distinctive, non-generic typography, spacing hierarchy, subtle contrast, and production aesthetics. 2. **`vercel-react-best-practices`**: Enforces strict React Server Components vs Client Components boundaries, memoization guidelines, and Next.js App Router idioms. 3. **`performance-optimization`**: Real-world bundle size reductions, image optimization, dynamic imports, and Core Web Vitals protections. ## Installation ```bash # Add the complete suite to your project npx skills add vercel-labs/agent-skills # Add only the web design guidelines for Claude Code npx skills add vercel-labs/agent-skills --skill web-design-guidelines -a claude-code ```
- SKILL.md (2886 bytes)
--- name: vercel-composition-patterns description: React composition patterns that scale. Use when refactoring components with boolean prop proliferation, building flexible component libraries, or designing reusable APIs. Triggers on tasks involving compound components, render props, context providers, or component architecture. Includes React 19 API changes. license: MIT metadata: author: vercel version: '1.0.0' --- # React Composition Patterns Composition patterns for building flexible, maintainable React components. Avoid boolean prop proliferation by using compound components, lifting state, and composing internals. These patterns make codebases easier for both humans and AI agents to work with as they scale. ## When to Apply Reference these guidelines when: - Refactoring components with many boolean props - Building reusable component libraries - Designing flexible component APIs - Reviewing component architecture - Working with compound components or context providers ## Rule Categories by Priority | Priority | Category | Impact | Prefix | | -------- | ----------------------- | ------ | --------------- | | 1 | Component Architecture | HIGH | `architecture-` | | 2 | State Management | MEDIUM | `state-` | | 3 | Implementation Patterns | MEDIUM | `patterns-` | | 4 | React 19 APIs | MEDIUM | `react19-` | ## Quick Reference ### 1. Component Architecture (HIGH) - `architecture-avoid-boolean-props` - Don't add boolean props to customize behavior; use composition - `architecture-compound-components` - Structure complex components with shared context ### 2. State Management (MEDIUM) - `state-decouple-implementation` - Provider is the only place that knows how state is managed - `state-context-interface` - Define generic interface with state, actions, meta for dependency injection - `state-lift-state` - Move state into provider components for sibling access ### 3. Implementation Patterns (MEDIUM) - `patterns-explicit-variants` - Create explicit variant components instead of boolean modes - `patterns-children-over-render-props` - Use children for composition instead of renderX props ### 4. React 19 APIs (MEDIUM) > **⚠️ React 19+ only.** Skip this section if using React 18 or earlier. - `react19-no-forwardref` - Don't use `forwardRef`; use `use()` instead of `useContext()` ## How to Use Read individual rule files for detailed explanations and code examples: ``` rules/architecture-avoid-boolean-props.md rules/state-context-interface.md ``` Each rule file contains: - Brief explanation of why it matters - Incorrect code example with explanation - Correct code example with explanation - Additional context and references ## Full Compiled Document For the complete guide with all rules expanded: `AGENTS.md`
- skills/composition-patterns/AGENTS.md (22627 bytes)
# React Composition Patterns **Version 1.0.0** Engineering January 2026 > **Note:** > This document is mainly for agents and LLMs to follow when maintaining, > generating, or refactoring React codebases using composition. Humans > may also find it useful, but guidance here is optimized for automation > and consistency by AI-assisted workflows. --- ## Abstract Composition patterns for building flexible, maintainable React components. Avoid boolean prop proliferation by using compound components, lifting state, and composing internals. These patterns make codebases easier for both humans and AI agents to work with as they scale. --- ## Table of Contents 1. [Component Architecture](#1-component-architecture) — **HIGH** - 1.1 [Avoid Boolean Prop Proliferation](#11-avoid-boolean-prop-proliferation) - 1.2 [Use Compound Components](#12-use-compound-components) 2. [State Management](#2-state-management) — **MEDIUM** - 2.1 [Decouple State Management from UI](#21-decouple-state-management-from-ui) - 2.2 [Define Generic Context Interfaces for Dependency Injection](#22-define-generic-context-interfaces-for-dependency-injection) - 2.3 [Lift State into Provider Components](#23-lift-state-into-provider-components) 3. [Implementation Patterns](#3-implementation-patterns) — **MEDIUM** - 3.1 [Create Explicit Component Variants](#31-create-explicit-component-variants) - 3.2 [Prefer Composing Children Over Render Props](#32-prefer-composing-children-over-render-props) 4. [React 19 APIs](#4-react-19-apis) — **MEDIUM** - 4.1 [React 19 API Changes](#41-react-19-api-changes) --- ## 1. Component Architecture **Impact: HIGH** Fundamental patterns for structuring components to avoid prop proliferation and enable flexible composition. ### 1.1 Avoid Boolean Prop Proliferation **Impact: CRITICAL (prevents unmaintainable component variants)** Don't add boolean props like `isThread`, `isEditing`, `isDMThread` to customize component behavior. Each boolean doubles possible states and creates unmaintainable conditional logic. Use composition instead. **Incorrect: boolean props create exponential complexity** ```tsx function Composer({ onSubmit, isThread, channelId, isDMThread, dmId, isEditing, isForwarding, }: Props) { return ( <form> <Header /> <Input /> {isDMThread ? ( <AlsoSendToDMField id={dmId} /> ) : isThread ? ( <AlsoSendToChannelField id={channelId} /> ) : null} {isEditing ? ( <EditActions /> ) : isForwarding ? ( <ForwardActions /> ) : ( <DefaultActions /> )} <Footer onSubmit={onSubmit} /> </form> ) } ``` **Correct: composition eliminates conditionals** ```tsx // Channel composer function ChannelComposer() { return ( <Composer.Frame> <Composer.Header /> <Composer.Input /> <Composer.Footer> <Composer.Attachments /> <Composer.Formatting /> <Composer.Emojis /> <Composer.Submit /> </Composer.Footer> </Composer.Frame> ) } // Thread composer - adds "also send to channel" field function ThreadComposer({ channelId }: { channelId: string }) { return ( <Composer.Frame> <Composer.Header /> <Composer.Input /> <AlsoSendToChannelField id={channelId} /> <Composer.Footer> <Composer.Formatting /> <Composer.Emojis /> <Composer.Submit /> </Composer.Footer> </Composer.Frame> ) } // Edit composer - different footer actions function EditComposer() { return ( <Composer.Frame> <Composer.Input /> <Composer.Footer> <Composer.Formatting /> <Composer.Emojis /> <Composer.CancelEdit /> <Composer.SaveEdit /> </Composer.Footer> </Composer.Frame> ) } ``` Each variant is explicit about what it renders. We can share internals without sharing a single monolithic parent. ### 1.2 Use Compound Components **Impact: HIGH (enables flexible composition without prop drilling)** Structure complex components as compound components with a shared context. Each subcomponent accesses shared state via context, not props. Consumers compose the pieces they need. **Incorrect: monolithic component with render props** ```tsx function Composer({ renderHeader, renderFooter, renderActions, showAttachments, showFormatting, showEmojis, }: Props) { return ( <form> {renderHeader?.()} <Input /> {showAttachments && <Attachments />} {renderFooter ? ( renderFooter() ) : ( <Footer> {showFormatting && <Formatting />} {showEmojis && <Emojis />} {renderActions?.()} </Footer> )} </form> ) } ``` **Correct: compound components with shared context** ```tsx const ComposerContext = createContext<ComposerContextValue | null>(null) function ComposerProvider({ children, state, actions, meta }: ProviderProps) { return ( <ComposerContext value={{ state, actions, meta }}> {children} </ComposerContext> ) } function ComposerFrame({ children }: { children: React.ReactNode }) { return <form>{children}</form> } function ComposerInput() { const { state, actions: { update }, meta: { inputRef }, } = use(ComposerContext) return ( <TextInput ref={inputRef} value={state.input} onChangeText={(text) => update((s) => ({ ...s, input: text }))} /> ) } function ComposerSubmit() { const { actions: { submit }, } = use(ComposerContext) return <Button onPress={submit}>Send</Button> } // Export as compound component const Composer = { Provider: ComposerProvider, Frame: ComposerFrame, Input: ComposerInput, Submit: ComposerSubmit, Header: ComposerHeader, Footer: ComposerFooter, Attachments: ComposerAttachments, Formatting: ComposerFormatting, Emojis: ComposerEmojis, } ``` **Usage:** ```tsx <Composer.Provider state={state} actions={actions} meta={meta}> <Composer.Frame> <Composer.Header /> <Composer.Input /> <Composer.Footer> <Composer.Formatting /> <Composer.Submit /> </Composer.Footer> </Composer.Frame> </Composer.Provider> ``` Consumers explicitly compose exactly what they need. No hidden conditionals. And the state, actions and meta are dependency-injected by a parent provider, allowing multiple usages of the same component structure. --- ## 2. State Management **Impact: MEDIUM** Patterns for lifting state and managing shared context across composed components. ### 2.1 Decouple State Management from UI **Impact: MEDIUM (enables swapping state implementations without changing UI)** The provider component should be the only place that knows how state is managed. UI components consume the context interface—they don't know if state comes from useState, Zustand, or a server sync. **Incorrect: UI coupled to state implementation** ```tsx function ChannelComposer({ channelId }: { channelId: string }) { // UI component knows about global state implementation const state = useGlobalChannelState(channelId) const { submit, updateInput } = useChannelSync(channelId) return ( <Composer.Frame> <Composer.Input value={state.input} onChange={(text) => sync.updateInput(text)} /> <Composer.Submit onPress={() => sync.submit()} /> </Composer.Frame> ) } ``` **Correct: state management isolated in provider** ```tsx // Provider handles all state management details function ChannelProvider({ channelId, children, }: { channelId: string children: React.ReactNode }) { const { state, update, submit } = useGlobalChannel(channelId) const inputRef = useRef(null) return ( <Composer.Provider state={state} actions={{ update, submit }} meta={{ inputRef }} > {children} </Composer.Provider> ) } // UI component only knows about the context interface function ChannelComposer() { return ( <Composer.Frame> <Composer.Header /> <Composer.Input /> <Composer.Footer> <Composer.Submit /> </Composer.Footer> </Composer.Frame> ) } // Usage function Channel({ channelId }: { channelId: string }) { return ( <ChannelProvider channelId={channelId}> <ChannelComposer /> </ChannelProvider> ) } ``` **Different providers, same UI:** ```tsx // Local state for ephemeral forms function ForwardMessageProvider({ children }) { const [state, setState] = useState(initialState) const forwardMessage = useForwardMessage() return ( <Composer.Provider state={state} actions={{ update: setState, submit: forwardMessage }} > {children} </Composer.Provider> ) } // Global synced state for channels function ChannelProvider({ channelId, children }) { const { state, update, submit } = useGlobalChannel(channelId) return ( <Composer.Provider state={state} actions={{ update, submit }}> {children} </Composer.Provider> ) } ``` The same `Composer.Input` component works with both providers because it only depends on the context interface, not the implementation. ### 2.2 Define Generic Context Interfaces for Dependency Injection **Impact: HIGH (enables dependency-injectable state across use-cases)** Define a **generic interface** for your component context with three parts: `state`, `actions`, and `meta`. This interface is a contract that any provider can implement—enabling the same UI components to work with completely different state implementations. **Core principle:** Lift state, compose internals, make state dependency-injectable. **Incorrect: UI coupled to specific state implementation** ```tsx function ComposerInput() { // Tightly coupled to a specific hook const { input, setInput } = useChannelComposerState() return <TextInput value={input} onChangeText={setInput} /> } ``` **Correct: generic interface enables dependency injection** ```tsx // Define a GENERIC interface that any provider can implement interface ComposerState { input: string attachments: Attachment[] isSubmitting: boolean } interface ComposerActions { update: (updater: (state: ComposerState) => ComposerState) => void submit: () => void } interface ComposerMeta { inputRef: React.RefObject<TextInput> } interface ComposerContextValue { state: ComposerState actions: ComposerActions meta: ComposerMeta } const ComposerContext = createContext<ComposerContextValue | null>(null) ``` **UI components consume the interface, not the implementation:** ```tsx function ComposerInput() { const { state, actions: { update }, meta, } = use(ComposerContext) // This component works with ANY provider that implements the interface return ( <TextInput ref={meta.inputRef} value={state.input} onChangeText={(text) => update((s) => ({ ...s, input: text }))} /> ) } ``` **Different providers implement the same interface:** ```tsx // Provider A: Local state for ephemeral forms function ForwardMessageProvider({ children }: { children: React.ReactNode }) { const [state, setState] = useState(initialState) const inputRef = useRef(null) const submit = useForwardMessage() return ( <ComposerContext value={{ state, actions: { update: setState, submit }, meta: { inputRef }, }} > {children} </ComposerContext> ) } // Provider B: Global synced state for channels function ChannelProvider({ channelId, children }: Props) { const { state, update, submit } = useGlobalChannel(channelId) const inputRef = useRef(null) return ( <ComposerContext value={{ state, actions: { update, submit }, meta: { inputRef }, }} > {children} </ComposerContext> ) } ``` **The same composed UI works with both:** ```tsx // Works with ForwardMessageProvider (local state) <ForwardMessageProvider> <Composer.Frame> <Composer.Input /> <Composer.Submit /> </Composer.Frame> </ForwardMessageProvider> // Works with ChannelProvider (global synced state) <ChannelProvider channelId="abc"> <Composer.Frame> <Composer.Input /> <Composer.Submit /> </Composer.Frame> </ChannelProvider> ``` **Custom UI outside the component can access state and actions:** ```tsx function ForwardMessageDialog() { return ( <ForwardMessageProvider> <Dialog> {/* The composer UI */} <Composer.Frame> <Composer.Input placeholder="Add a message, if you'd like." /> <Composer.Footer> <Composer.Formatting /> <Composer.Emojis /> </Composer.Footer> </Composer.Frame> {/* Custom UI OUTSIDE the composer, but INSIDE the provider */} <MessagePreview /> {/* Actions at the bottom of the dialog */} <DialogActions> <CancelButton /> <ForwardButton /> </DialogActions> </Dialog> </ForwardMessageProvider> ) } // This button lives OUTSIDE Composer.Frame but can still submit based on its context! function ForwardButton() { const { actions: { submit }, } = use(ComposerContext) return <Button onPress={submit}>Forward</Button> } // This preview lives OUTSIDE Composer.Frame but can read composer's state! function MessagePreview() { const { state } = use(ComposerContext) return <Preview message={state.input} attachments={state.attachments} /> } ``` The provider boundary is what matters—not the visual nesting. Components that need shared state don't have to be inside the `Composer.Frame`. They just need to be within the provider. The `ForwardButton` and `MessagePreview` are not visually inside the composer box, but they can still access its state and actions. This is the power of lifting state into providers. The UI is reusable bits you compose together. The state is dependency-injected by the provider. Swap the provider, keep the UI. ### 2.3 Lift State into Provider Components **Impact: HIGH (enables state sharing outside component boundaries)** Move state management into dedicated provider components. This allows sibling components outside the main UI to access and modify state without prop drilling or awkward refs. **Incorrect: state trapped inside component** ```tsx function ForwardMessageComposer() { const [state, setState] = useState(initialState) const forwardMessage = useForwardMessage() return ( <Composer.Frame> <Composer.Input /> <Composer.Footer /> </Composer.Frame> ) } // Problem: How does this button access composer state? function ForwardMessageDialog() { return ( <Dialog> <ForwardMessageComposer /> <MessagePreview /> {/* Needs composer state */} <DialogActions> <CancelButton /> <ForwardButton /> {/* Needs to call submit */} </DialogActions> </Dialog> ) } ``` **Incorrect: useEffect to sync state up - skills/composition-patterns/metadata.json (530 bytes)
{ "version": "1.0.0", "organization": "Engineering", "date": "January 2026", "abstract": "Composition patterns for building flexible, maintainable React components. Avoid boolean prop proliferation by using compound components, lifting state, and composing internals. These patterns make codebases easier for both humans and AI agents to work with as they scale.", "references": [ "https://react.dev", "https://react.dev/learn/passing-data-deeply-with-context", "https://react.dev/reference/react/use" ] } - skills/composition-patterns/README.md (2140 bytes)
# React Composition Patterns A structured repository for React composition patterns that scale. These patterns help avoid boolean prop proliferation by using compound components, lifting state, and composing internals. ## Structure - `rules/` - Individual rule files (one per rule) - `_sections.md` - Section metadata (titles, impacts, descriptions) - `_template.md` - Template for creating new rules - `area-description.md` - Individual rule files - `metadata.json` - Document metadata (version, organization, abstract) - **`AGENTS.md`** - Compiled output (generated) ## Rules ### Component Architecture (CRITICAL) - `architecture-avoid-boolean-props.md` - Don't add boolean props to customize behavior - `architecture-compound-components.md` - Structure as compound components with shared context ### State Management (HIGH) - `state-lift-state.md` - Lift state into provider components - `state-context-interface.md` - Define clear context interfaces (state/actions/meta) - `state-decouple-implementation.md` - Decouple state management from UI ### Implementation Patterns (MEDIUM) - `patterns-children-over-render-props.md` - Prefer children over renderX props - `patterns-explicit-variants.md` - Create explicit component variants ## Core Principles 1. **Composition over configuration** — Instead of adding props, let consumers compose 2. **Lift your state** — State in providers, not trapped in components 3. **Compose your internals** — Subcomponents access context, not props 4. **Explicit variants** — Create ThreadComposer, EditComposer, not Composer with isThread ## Creating a New Rule 1. Copy `rules/_template.md` to `rules/area-description.md` 2. Choose the appropriate area prefix: - `architecture-` for Component Architecture - `state-` for State Management - `patterns-` for Implementation Patterns 3. Fill in the frontmatter and content 4. Ensure you have clear examples with explanations ## Impact Levels - `CRITICAL` - Foundational patterns, prevents unmaintainable code - `HIGH` - Significant maintainability improvements - `MEDIUM` - Good practices for cleaner code
- skills/composition-patterns/rules/_sections.md (829 bytes)
# Sections This file defines all sections, their ordering, impact levels, and descriptions. The section ID (in parentheses) is the filename prefix used to group rules. --- ## 1. Component Architecture (architecture) **Impact:** HIGH **Description:** Fundamental patterns for structuring components to avoid prop proliferation and enable flexible composition. ## 2. State Management (state) **Impact:** MEDIUM **Description:** Patterns for lifting state and managing shared context across composed components. ## 3. Implementation Patterns (patterns) **Impact:** MEDIUM **Description:** Specific techniques for implementing compound components and context providers. ## 4. React 19 APIs (react19) **Impact:** MEDIUM **Description:** React 19+ only. Don't use `forwardRef`; use `use()` instead of `useContext()`.
- skills/composition-patterns/rules/_template.md (329 bytes)
--- title: Rule Title Here impact: MEDIUM impactDescription: brief description of impact tags: composition, components --- ## Rule Title Here Brief explanation of the rule and why it matters. **Incorrect:** ```tsx // Bad code example ``` **Correct:** ```tsx // Good code example ``` Reference: [Link](https://example.com)
- skills/composition-patterns/rules/architecture-avoid-boolean-props.md (2267 bytes)
--- title: Avoid Boolean Prop Proliferation impact: CRITICAL impactDescription: prevents unmaintainable component variants tags: composition, props, architecture --- ## Avoid Boolean Prop Proliferation Don't add boolean props like `isThread`, `isEditing`, `isDMThread` to customize component behavior. Each boolean doubles possible states and creates unmaintainable conditional logic. Use composition instead. **Incorrect (boolean props create exponential complexity):** ```tsx function Composer({ onSubmit, isThread, channelId, isDMThread, dmId, isEditing, isForwarding, }: Props) { return ( <form> <Header /> <Input /> {isDMThread ? ( <AlsoSendToDMField id={dmId} /> ) : isThread ? ( <AlsoSendToChannelField id={channelId} /> ) : null} {isEditing ? ( <EditActions /> ) : isForwarding ? ( <ForwardActions /> ) : ( <DefaultActions /> )} <Footer onSubmit={onSubmit} /> </form> ) } ``` **Correct (composition eliminates conditionals):** ```tsx // Channel composer function ChannelComposer() { return ( <Composer.Frame> <Composer.Header /> <Composer.Input /> <Composer.Footer> <Composer.Attachments /> <Composer.Formatting /> <Composer.Emojis /> <Composer.Submit /> </Composer.Footer> </Composer.Frame> ) } // Thread composer - adds "also send to channel" field function ThreadComposer({ channelId }: { channelId: string }) { return ( <Composer.Frame> <Composer.Header /> <Composer.Input /> <AlsoSendToChannelField id={channelId} /> <Composer.Footer> <Composer.Formatting /> <Composer.Emojis /> <Composer.Submit /> </Composer.Footer> </Composer.Frame> ) } // Edit composer - different footer actions function EditComposer() { return ( <Composer.Frame> <Composer.Input /> <Composer.Footer> <Composer.Formatting /> <Composer.Emojis /> <Composer.CancelEdit /> <Composer.SaveEdit /> </Composer.Footer> </Composer.Frame> ) } ``` Each variant is explicit about what it renders. We can share internals without sharing a single monolithic parent. - skills/composition-patterns/rules/architecture-compound-components.md (2600 bytes)
--- title: Use Compound Components impact: HIGH impactDescription: enables flexible composition without prop drilling tags: composition, compound-components, architecture --- ## Use Compound Components Structure complex components as compound components with a shared context. Each subcomponent accesses shared state via context, not props. Consumers compose the pieces they need. **Incorrect (monolithic component with render props):** ```tsx function Composer({ renderHeader, renderFooter, renderActions, showAttachments, showFormatting, showEmojis, }: Props) { return ( <form> {renderHeader?.()} <Input /> {showAttachments && <Attachments />} {renderFooter ? ( renderFooter() ) : ( <Footer> {showFormatting && <Formatting />} {showEmojis && <Emojis />} {renderActions?.()} </Footer> )} </form> ) } ``` **Correct (compound components with shared context):** ```tsx const ComposerContext = createContext<ComposerContextValue | null>(null) function ComposerProvider({ children, state, actions, meta }: ProviderProps) { return ( <ComposerContext value={{ state, actions, meta }}> {children} </ComposerContext> ) } function ComposerFrame({ children }: { children: React.ReactNode }) { return <form>{children}</form> } function ComposerInput() { const { state, actions: { update }, meta: { inputRef }, } = use(ComposerContext) return ( <TextInput ref={inputRef} value={state.input} onChangeText={(text) => update((s) => ({ ...s, input: text }))} /> ) } function ComposerSubmit() { const { actions: { submit }, } = use(ComposerContext) return <Button onPress={submit}>Send</Button> } // Export as compound component const Composer = { Provider: ComposerProvider, Frame: ComposerFrame, Input: ComposerInput, Submit: ComposerSubmit, Header: ComposerHeader, Footer: ComposerFooter, Attachments: ComposerAttachments, Formatting: ComposerFormatting, Emojis: ComposerEmojis, } ``` **Usage:** ```tsx <Composer.Provider state={state} actions={actions} meta={meta}> <Composer.Frame> <Composer.Header /> <Composer.Input /> <Composer.Footer> <Composer.Formatting /> <Composer.Submit /> </Composer.Footer> </Composer.Frame> </Composer.Provider> ``` Consumers explicitly compose exactly what they need. No hidden conditionals. And the state, actions and meta are dependency-injected by a parent provider, allowing multiple usages of the same component structure. - skills/composition-patterns/rules/patterns-children-over-render-props.md (1886 bytes)
--- title: Prefer Composing Children Over Render Props impact: MEDIUM impactDescription: cleaner composition, better readability tags: composition, children, render-props --- ## Prefer Children Over Render Props Use `children` for composition instead of `renderX` props. Children are more readable, compose naturally, and don't require understanding callback signatures. **Incorrect (render props):** ```tsx function Composer({ renderHeader, renderFooter, renderActions, }: { renderHeader?: () => React.ReactNode renderFooter?: () => React.ReactNode renderActions?: () => React.ReactNode }) { return ( <form> {renderHeader?.()} <Input /> {renderFooter ? renderFooter() : <DefaultFooter />} {renderActions?.()} </form> ) } // Usage is awkward and inflexible return ( <Composer renderHeader={() => <CustomHeader />} renderFooter={() => ( <> <Formatting /> <Emojis /> </> )} renderActions={() => <SubmitButton />} /> ) ``` **Correct (compound components with children):** ```tsx function ComposerFrame({ children }: { children: React.ReactNode }) { return <form>{children}</form> } function ComposerFooter({ children }: { children: React.ReactNode }) { return <footer className='flex'>{children}</footer> } // Usage is flexible return ( <Composer.Frame> <CustomHeader /> <Composer.Input /> <Composer.Footer> <Composer.Formatting /> <Composer.Emojis /> <SubmitButton /> </Composer.Footer> </Composer.Frame> ) ``` **When render props are appropriate:** ```tsx // Render props work well when you need to pass data back <List data={items} renderItem={({ item, index }) => <Item item={item} index={index} />} /> ``` Use render props when the parent needs to provide data or state to the child. Use children when composing static structure. - skills/composition-patterns/rules/patterns-explicit-variants.md (2395 bytes)
--- title: Create Explicit Component Variants impact: MEDIUM impactDescription: self-documenting code, no hidden conditionals tags: composition, variants, architecture --- ## Create Explicit Component Variants Instead of one component with many boolean props, create explicit variant components. Each variant composes the pieces it needs. The code documents itself. **Incorrect (one component, many modes):** ```tsx // What does this component actually render? <Composer isThread isEditing={false} channelId='abc' showAttachments showFormatting={false} /> ``` **Correct (explicit variants):** ```tsx // Immediately clear what this renders <ThreadComposer channelId="abc" /> // Or <EditMessageComposer messageId="xyz" /> // Or <ForwardMessageComposer messageId="123" /> ``` Each implementation is unique, explicit and self-contained. Yet they can each use shared parts. **Implementation:** ```tsx function ThreadComposer({ channelId }: { channelId: string }) { return ( <ThreadProvider channelId={channelId}> <Composer.Frame> <Composer.Input /> <AlsoSendToChannelField channelId={channelId} /> <Composer.Footer> <Composer.Formatting /> <Composer.Emojis /> <Composer.Submit /> </Composer.Footer> </Composer.Frame> </ThreadProvider> ) } function EditMessageComposer({ messageId }: { messageId: string }) { return ( <EditMessageProvider messageId={messageId}> <Composer.Frame> <Composer.Input /> <Composer.Footer> <Composer.Formatting /> <Composer.Emojis /> <Composer.CancelEdit /> <Composer.SaveEdit /> </Composer.Footer> </Composer.Frame> </EditMessageProvider> ) } function ForwardMessageComposer({ messageId }: { messageId: string }) { return ( <ForwardMessageProvider messageId={messageId}> <Composer.Frame> <Composer.Input placeholder="Add a message, if you'd like." /> <Composer.Footer> <Composer.Formatting /> <Composer.Emojis /> <Composer.Mentions /> </Composer.Footer> </Composer.Frame> </ForwardMessageProvider> ) } ``` Each variant is explicit about: - What provider/state it uses - What UI elements it includes - What actions are available No boolean prop combinations to reason about. No impossible states. - skills/composition-patterns/rules/react19-no-forwardref.md (953 bytes)
--- title: React 19 API Changes impact: MEDIUM impactDescription: cleaner component definitions and context usage tags: react19, refs, context, hooks --- ## React 19 API Changes > **⚠️ React 19+ only.** Skip this if you're on React 18 or earlier. In React 19, `ref` is now a regular prop (no `forwardRef` wrapper needed), and `use()` replaces `useContext()`. **Incorrect (forwardRef in React 19):** ```tsx const ComposerInput = forwardRef<TextInput, Props>((props, ref) => { return <TextInput ref={ref} {...props} /> }) ``` **Correct (ref as a regular prop):** ```tsx function ComposerInput({ ref, ...props }: Props & { ref?: React.Ref<TextInput> }) { return <TextInput ref={ref} {...props} /> } ``` **Incorrect (useContext in React 19):** ```tsx const value = useContext(MyContext) ``` **Correct (use instead of useContext):** ```tsx const value = use(MyContext) ``` `use()` can also be called conditionally, unlike `useContext()`. - skills/composition-patterns/rules/state-context-interface.md (4974 bytes)
--- title: Define Generic Context Interfaces for Dependency Injection impact: HIGH impactDescription: enables dependency-injectable state across use-cases tags: composition, context, state, typescript, dependency-injection --- ## Define Generic Context Interfaces for Dependency Injection Define a **generic interface** for your component context with three parts: `state`, `actions`, and `meta`. This interface is a contract that any provider can implement—enabling the same UI components to work with completely different state implementations. **Core principle:** Lift state, compose internals, make state dependency-injectable. **Incorrect (UI coupled to specific state implementation):** ```tsx function ComposerInput() { // Tightly coupled to a specific hook const { input, setInput } = useChannelComposerState() return <TextInput value={input} onChangeText={setInput} /> } ``` **Correct (generic interface enables dependency injection):** ```tsx // Define a GENERIC interface that any provider can implement interface ComposerState { input: string attachments: Attachment[] isSubmitting: boolean } interface ComposerActions { update: (updater: (state: ComposerState) => ComposerState) => void submit: () => void } interface ComposerMeta { inputRef: React.RefObject<TextInput> } interface ComposerContextValue { state: ComposerState actions: ComposerActions meta: ComposerMeta } const ComposerContext = createContext<ComposerContextValue | null>(null) ``` **UI components consume the interface, not the implementation:** ```tsx function ComposerInput() { const { state, actions: { update }, meta, } = use(ComposerContext) // This component works with ANY provider that implements the interface return ( <TextInput ref={meta.inputRef} value={state.input} onChangeText={(text) => update((s) => ({ ...s, input: text }))} /> ) } ``` **Different providers implement the same interface:** ```tsx // Provider A: Local state for ephemeral forms function ForwardMessageProvider({ children }: { children: React.ReactNode }) { const [state, setState] = useState(initialState) const inputRef = useRef(null) const submit = useForwardMessage() return ( <ComposerContext value={{ state, actions: { update: setState, submit }, meta: { inputRef }, }} > {children} </ComposerContext> ) } // Provider B: Global synced state for channels function ChannelProvider({ channelId, children }: Props) { const { state, update, submit } = useGlobalChannel(channelId) const inputRef = useRef(null) return ( <ComposerContext value={{ state, actions: { update, submit }, meta: { inputRef }, }} > {children} </ComposerContext> ) } ``` **The same composed UI works with both:** ```tsx // Works with ForwardMessageProvider (local state) <ForwardMessageProvider> <Composer.Frame> <Composer.Input /> <Composer.Submit /> </Composer.Frame> </ForwardMessageProvider> // Works with ChannelProvider (global synced state) <ChannelProvider channelId="abc"> <Composer.Frame> <Composer.Input /> <Composer.Submit /> </Composer.Frame> </ChannelProvider> ``` **Custom UI outside the component can access state and actions:** The provider boundary is what matters—not the visual nesting. Components that need shared state don't have to be inside the `Composer.Frame`. They just need to be within the provider. ```tsx function ForwardMessageDialog() { return ( <ForwardMessageProvider> <Dialog> {/* The composer UI */} <Composer.Frame> <Composer.Input placeholder="Add a message, if you'd like." /> <Composer.Footer> <Composer.Formatting /> <Composer.Emojis /> </Composer.Footer> </Composer.Frame> {/* Custom UI OUTSIDE the composer, but INSIDE the provider */} <MessagePreview /> {/* Actions at the bottom of the dialog */} <DialogActions> <CancelButton /> <ForwardButton /> </DialogActions> </Dialog> </ForwardMessageProvider> ) } // This button lives OUTSIDE Composer.Frame but can still submit based on its context! function ForwardButton() { const { actions: { submit }, } = use(ComposerContext) return <Button onPress={submit}>Forward</Button> } // This preview lives OUTSIDE Composer.Frame but can read composer's state! function MessagePreview() { const { state } = use(ComposerContext) return <Preview message={state.input} attachments={state.attachments} /> } ``` The `ForwardButton` and `MessagePreview` are not visually inside the composer box, but they can still access its state and actions. This is the power of lifting state into providers. The UI is reusable bits you compose together. The state is dependency-injected by the provider. Swap the provider, keep the UI. - skills/composition-patterns/rules/state-decouple-implementation.md (2699 bytes)
--- title: Decouple State Management from UI impact: MEDIUM impactDescription: enables swapping state implementations without changing UI tags: composition, state, architecture --- ## Decouple State Management from UI The provider component should be the only place that knows how state is managed. UI components consume the context interface—they don't know if state comes from useState, Zustand, or a server sync. **Incorrect (UI coupled to state implementation):** ```tsx function ChannelComposer({ channelId }: { channelId: string }) { // UI component knows about global state implementation const state = useGlobalChannelState(channelId) const { submit, updateInput } = useChannelSync(channelId) return ( <Composer.Frame> <Composer.Input value={state.input} onChange={(text) => sync.updateInput(text)} /> <Composer.Submit onPress={() => sync.submit()} /> </Composer.Frame> ) } ``` **Correct (state management isolated in provider):** ```tsx // Provider handles all state management details function ChannelProvider({ channelId, children, }: { channelId: string children: React.ReactNode }) { const { state, update, submit } = useGlobalChannel(channelId) const inputRef = useRef(null) return ( <Composer.Provider state={state} actions={{ update, submit }} meta={{ inputRef }} > {children} </Composer.Provider> ) } // UI component only knows about the context interface function ChannelComposer() { return ( <Composer.Frame> <Composer.Header /> <Composer.Input /> <Composer.Footer> <Composer.Submit /> </Composer.Footer> </Composer.Frame> ) } // Usage function Channel({ channelId }: { channelId: string }) { return ( <ChannelProvider channelId={channelId}> <ChannelComposer /> </ChannelProvider> ) } ``` **Different providers, same UI:** ```tsx // Local state for ephemeral forms function ForwardMessageProvider({ children }) { const [state, setState] = useState(initialState) const forwardMessage = useForwardMessage() return ( <Composer.Provider state={state} actions={{ update: setState, submit: forwardMessage }} > {children} </Composer.Provider> ) } // Global synced state for channels function ChannelProvider({ channelId, children }) { const { state, update, submit } = useGlobalChannel(channelId) return ( <Composer.Provider state={state} actions={{ update, submit }}> {children} </Composer.Provider> ) } ``` The same `Composer.Input` component works with both providers because it only depends on the context interface, not the implementation. - skills/composition-patterns/rules/state-lift-state.md (3224 bytes)
--- title: Lift State into Provider Components impact: HIGH impactDescription: enables state sharing outside component boundaries tags: composition, state, context, providers --- ## Lift State into Provider Components Move state management into dedicated provider components. This allows sibling components outside the main UI to access and modify state without prop drilling or awkward refs. **Incorrect (state trapped inside component):** ```tsx function ForwardMessageComposer() { const [state, setState] = useState(initialState) const forwardMessage = useForwardMessage() return ( <Composer.Frame> <Composer.Input /> <Composer.Footer /> </Composer.Frame> ) } // Problem: How does this button access composer state? function ForwardMessageDialog() { return ( <Dialog> <ForwardMessageComposer /> <MessagePreview /> {/* Needs composer state */} <DialogActions> <CancelButton /> <ForwardButton /> {/* Needs to call submit */} </DialogActions> </Dialog> ) } ``` **Incorrect (useEffect to sync state up):** ```tsx function ForwardMessageDialog() { const [input, setInput] = useState('') return ( <Dialog> <ForwardMessageComposer onInputChange={setInput} /> <MessagePreview input={input} /> </Dialog> ) } function ForwardMessageComposer({ onInputChange }) { const [state, setState] = useState(initialState) useEffect(() => { onInputChange(state.input) // Sync on every change 😬 }, [state.input]) } ``` **Incorrect (reading state from ref on submit):** ```tsx function ForwardMessageDialog() { const stateRef = useRef(null) return ( <Dialog> <ForwardMessageComposer stateRef={stateRef} /> <ForwardButton onPress={() => submit(stateRef.current)} /> </Dialog> ) } ``` **Correct (state lifted to provider):** ```tsx function ForwardMessageProvider({ children }: { children: React.ReactNode }) { const [state, setState] = useState(initialState) const forwardMessage = useForwardMessage() const inputRef = useRef(null) return ( <Composer.Provider state={state} actions={{ update: setState, submit: forwardMessage }} meta={{ inputRef }} > {children} </Composer.Provider> ) } function ForwardMessageDialog() { return ( <ForwardMessageProvider> <Dialog> <ForwardMessageComposer /> <MessagePreview /> {/* Custom components can access state and actions */} <DialogActions> <CancelButton /> <ForwardButton /> {/* Custom components can access state and actions */} </DialogActions> </Dialog> </ForwardMessageProvider> ) } function ForwardButton() { const { actions } = use(Composer.Context) return <Button onPress={actions.submit}>Forward</Button> } ``` The ForwardButton lives outside the Composer.Frame but still has access to the submit action because it's within the provider. Even though it's a one-off component, it can still access the composer's state and actions from outside the UI itself. **Key insight:** Components that need shared state don't have to be visually nested inside each other—they just need to be within the same provider. - skills/composition-patterns/SKILL.md (2886 bytes)
--- name: vercel-composition-patterns description: React composition patterns that scale. Use when refactoring components with boolean prop proliferation, building flexible component libraries, or designing reusable APIs. Triggers on tasks involving compound components, render props, context providers, or component architecture. Includes React 19 API changes. license: MIT metadata: author: vercel version: '1.0.0' --- # React Composition Patterns Composition patterns for building flexible, maintainable React components. Avoid boolean prop proliferation by using compound components, lifting state, and composing internals. These patterns make codebases easier for both humans and AI agents to work with as they scale. ## When to Apply Reference these guidelines when: - Refactoring components with many boolean props - Building reusable component libraries - Designing flexible component APIs - Reviewing component architecture - Working with compound components or context providers ## Rule Categories by Priority | Priority | Category | Impact | Prefix | | -------- | ----------------------- | ------ | --------------- | | 1 | Component Architecture | HIGH | `architecture-` | | 2 | State Management | MEDIUM | `state-` | | 3 | Implementation Patterns | MEDIUM | `patterns-` | | 4 | React 19 APIs | MEDIUM | `react19-` | ## Quick Reference ### 1. Component Architecture (HIGH) - `architecture-avoid-boolean-props` - Don't add boolean props to customize behavior; use composition - `architecture-compound-components` - Structure complex components with shared context ### 2. State Management (MEDIUM) - `state-decouple-implementation` - Provider is the only place that knows how state is managed - `state-context-interface` - Define generic interface with state, actions, meta for dependency injection - `state-lift-state` - Move state into provider components for sibling access ### 3. Implementation Patterns (MEDIUM) - `patterns-explicit-variants` - Create explicit variant components instead of boolean modes - `patterns-children-over-render-props` - Use children for composition instead of renderX props ### 4. React 19 APIs (MEDIUM) > **⚠️ React 19+ only.** Skip this section if using React 18 or earlier. - `react19-no-forwardref` - Don't use `forwardRef`; use `use()` instead of `useContext()` ## How to Use Read individual rule files for detailed explanations and code examples: ``` rules/architecture-avoid-boolean-props.md rules/state-context-interface.md ``` Each rule file contains: - Brief explanation of why it matters - Incorrect code example with explanation - Correct code example with explanation - Additional context and references ## Full Compiled Document For the complete guide with all rules expanded: `AGENTS.md`
- skills/deploy-to-vercel/SKILL.md (9721 bytes)
--- name: deploy-to-vercel description: Deploy applications and websites to Vercel. Use when the user requests deployment actions like "deploy my app", "deploy and give me the link", "push this live", or "create a preview deployment". metadata: author: vercel version: "4.0.0" --- # Deploy to Vercel Deploy any project to Vercel. **Always deploy as preview** (not production) unless the user explicitly asks for production. The goal is to get the user into the best long-term setup: their project linked to Vercel with git-push deploys. Every method below tries to move the user closer to that state. ## Step 1: Gather Project State Run all four checks before deciding which method to use: ```bash # 1. Check for a git remote git remote get-url origin 2>/dev/null # 2. Check if locally linked to a Vercel project (either file means linked) cat .vercel/project.json 2>/dev/null || cat .vercel/repo.json 2>/dev/null # 3. Check if the Vercel CLI is installed and authenticated vercel whoami 2>/dev/null # 4. List available teams (if authenticated) vercel teams list --format json 2>/dev/null ``` ### Team selection If the user belongs to multiple teams, present all available team slugs as a bulleted list and ask which one to deploy to. Once the user picks a team, proceed immediately to the next step — do not ask for additional confirmation. Pass the team slug via `--scope` on all subsequent CLI commands (`vercel deploy`, `vercel link`, `vercel inspect`, etc.): ```bash vercel deploy [path] -y --no-wait --scope <team-slug> ``` If the project is already linked (`.vercel/project.json` or `.vercel/repo.json` exists), the `orgId` in those files determines the team — no need to ask again. If there is only one team (or just a personal account), skip the prompt and use it directly. **About the `.vercel/` directory:** A linked project has either: - `.vercel/project.json` — created by `vercel link` (single project linking). Contains `projectId` and `orgId`. - `.vercel/repo.json` — created by `vercel link --repo` (repo-based linking). Contains `orgId`, `remoteName`, and a `projects` array mapping directories to Vercel project IDs. Either file means the project is linked. Check for both. **Do NOT** use `vercel project inspect`, `vercel ls`, or `vercel link` to detect state in an unlinked directory — without a `.vercel/` config, they will interactively prompt (or with `--yes`, silently link as a side-effect). Only `vercel whoami` is safe to run anywhere. ## Step 2: Choose a Deploy Method ### Linked (`.vercel/` exists) + has git remote → Git Push This is the ideal state. The project is linked and has git integration. 1. **Ask the user before pushing.** Never push without explicit approval: ``` This project is connected to Vercel via git. I can commit and push to trigger a deployment. Want me to proceed? ``` 2. **Commit and push:** ```bash git add . git commit -m "deploy: <description of changes>" git push ``` Vercel automatically builds from the push. Non-production branches get preview deployments; the production branch (usually `main`) gets a production deployment. 3. **Retrieve the preview URL.** If the CLI is authenticated: ```bash sleep 5 vercel ls --format json ``` The JSON output has a `deployments` array. Find the latest entry — its `url` field is the preview URL. If the CLI is not authenticated, tell the user to check the Vercel dashboard or the commit status checks on their git provider for the preview URL. --- ### Linked (`.vercel/` exists) + no git remote → `vercel deploy` The project is linked but there's no git repo. Deploy directly with the CLI. ```bash vercel deploy [path] -y --no-wait ``` Use `--no-wait` so the CLI returns immediately with the deployment URL instead of blocking until the build finishes (builds can take a while). Then check on the deployment status with: ```bash vercel inspect <deployment-url> ``` For production deploys (only if user explicitly asks): ```bash vercel deploy [path] --prod -y --no-wait ``` --- ### Not linked + CLI is authenticated → Link first, then deploy The CLI is working but the project isn't linked yet. This is the opportunity to get the user into the best state. 1. **Ask the user which team to deploy to.** Present the team slugs from Step 1 as a bulleted list. If there's only one team (or just a personal account), skip this step. 2. **Once a team is selected, proceed directly to linking.** Tell the user what will happen but do not ask for separate confirmation: ``` Linking this project to <team name> on Vercel. This will create a Vercel project to deploy to and enable automatic deployments on future git pushes. ``` 3. **If a git remote exists**, use repo-based linking with the selected team scope: ```bash vercel link --repo --scope <team-slug> ``` This reads the git remote URL and matches it to existing Vercel projects that deploy from that repo. It creates `.vercel/repo.json`. This is much more reliable than `vercel link` (without `--repo`), which tries to match by directory name and often fails when the local folder and Vercel project are named differently. **If there is no git remote**, fall back to standard linking: ```bash vercel link --scope <team-slug> ``` This prompts the user to select or create a project. It creates `.vercel/project.json`. 4. **Then deploy using the best available method:** - If a git remote exists → commit and push (see git push method above) - If no git remote → `vercel deploy [path] -y --no-wait --scope <team-slug>`, then `vercel inspect <url>` to check status --- ### Not linked + CLI not authenticated → Install, auth, link, deploy The Vercel CLI isn't set up at all. 1. **Install the CLI (if not already installed):** ```bash npm install -g vercel ``` 2. **Authenticate:** ```bash vercel login ``` The user completes auth in their browser. If running in a non-interactive environment where login is not possible, skip to the **no-auth fallback** below. 3. **Ask which team to deploy to** — present team slugs from `vercel teams list --format json` as a bulleted list. If only one team / personal account, skip. Once selected, proceed immediately. 4. **Link the project** with the selected team scope (use `--repo` if a git remote exists, plain `vercel link` otherwise): ```bash vercel link --repo --scope <team-slug> # if git remote exists vercel link --scope <team-slug> # if no git remote ``` 5. **Deploy** using the best available method (git push if remote exists, otherwise `vercel deploy -y --no-wait --scope <team-slug>`, then `vercel inspect <url>` to check status). --- ### No-Auth Fallback — `vercel deploy --temporary` **When to use:** The CLI has no credentials and `vercel login` isn't possible (sandboxes, agents, non-interactive environments). Do **not** ask the user to approve a CLI login or device code first — try this. ```bash npx vercel@latest deploy [path] --temporary -y ``` No account is needed. The CLI builds locally, deploys to a temporary production URL, and prints a **claim URL** plus how long until the deployment expires. Rerunning the command in the same directory redeploys the same temporary project until it expires. Temporary deployments don't work in CI or in a directory already linked to a Vercel project. See https://vercel.com/docs/deployments/deploy-without-logging-in. **Tell the user:** "Your deployment is ready at [url]. It expires in [time] unless you claim it at [claimUrl]. Don't share the claim link." **Escalated network access (Codex):** Only escalate the deploy command if sandboxing blocks the network call (`sandbox_permissions=require_escalated`). --- ## Agent-Specific Notes ### Claude Code / terminal-based agents You have full shell access. Follow the decision flow above using the CLI directly. ### Sandboxed environments (claude.ai, Codex) Check whether the CLI is logged in with `vercel whoami`. If it is, follow Step 2, including team selection. If it isn't, use the **no-auth fallback**. --- ## Output Always show the user the deployment URL. - **Git push:** Use `vercel ls --format json` to find the preview URL. If the CLI isn't authenticated, tell the user to check the Vercel dashboard or commit status checks. - **CLI deploy:** Show the URL returned by `vercel deploy --no-wait`. Use `vercel inspect <url>` to check build status and report it to the user. - **No-auth fallback:** Show the deployment URL, the claim URL, and the expiry the CLI printed. **Do not** curl or fetch the deployed URL to verify it works. Just return the link. --- ## Troubleshooting ### Network Egress Error (claude.ai) If deployment fails due to network restrictions on claude.ai, tell the user: ``` Deployment failed due to network restrictions. To fix this: 1. Go to https://claude.ai/settings/capabilities 2. Add *.vercel.com and registry.npmjs.org to the allowed domains 3. Try deploying again ``` ### Escalated Network Access (Codex / sandboxed environments) If deployment fails due to network issues (timeouts, DNS errors, connection resets) in a sandboxed environment, rerun with escalated permissions (`sandbox_permissions=require_escalated`). Do not escalate the initial CLI availability check — only escalate the actual deploy command. Example guidance to the user: ``` The deploy needs escalated network access to deploy to Vercel. I can rerun the command with escalated permissions — want me to proceed? ``` ### CLI Auth Failure If `vercel login` or `vercel deploy` fails with authentication errors, use the no-auth fallback: `vercel deploy --temporary -y`.
- skills/react-best-practices/AGENTS.md (108261 bytes)
# React Best Practices **Version 1.0.0** Vercel Engineering January 2026 > **Note:** > This document is mainly for agents and LLMs to follow when maintaining, > generating, or refactoring React and Next.js codebases. Humans > may also find it useful, but guidance here is optimized for automation > and consistency by AI-assisted workflows. --- ## Abstract Comprehensive performance optimization guide for React and Next.js applications, designed for AI agents and LLMs. Contains 40+ rules across 8 categories, prioritized by impact from critical (eliminating waterfalls, reducing bundle size) to incremental (advanced patterns). Each rule includes detailed explanations, real-world examples comparing incorrect vs. correct implementations, and specific impact metrics to guide automated refactoring and code generation. --- ## Table of Contents 1. [Eliminating Waterfalls](#1-eliminating-waterfalls) — **CRITICAL** - 1.1 [Check Cheap Conditions Before Async Flags](#11-check-cheap-conditions-before-async-flags) - 1.2 [Defer Await Until Needed](#12-defer-await-until-needed) - 1.3 [Dependency-Based Parallelization](#13-dependency-based-parallelization) - 1.4 [Prevent Waterfall Chains in API Routes](#14-prevent-waterfall-chains-in-api-routes) - 1.5 [Promise.all() for Independent Operations](#15-promiseall-for-independent-operations) - 1.6 [Strategic Suspense Boundaries](#16-strategic-suspense-boundaries) 2. [Bundle Size Optimization](#2-bundle-size-optimization) — **CRITICAL** - 2.1 [Avoid Barrel File Imports](#21-avoid-barrel-file-imports) - 2.2 [Conditional Module Loading](#22-conditional-module-loading) - 2.3 [Defer Non-Critical Third-Party Libraries](#23-defer-non-critical-third-party-libraries) - 2.4 [Dynamic Imports for Heavy Components](#24-dynamic-imports-for-heavy-components) - 2.5 [Prefer Statically Analyzable Paths](#25-prefer-statically-analyzable-paths) - 2.6 [Preload Based on User Intent](#26-preload-based-on-user-intent) 3. [Server-Side Performance](#3-server-side-performance) — **HIGH** - 3.1 [Authenticate Server Actions Like API Routes](#31-authenticate-server-actions-like-api-routes) - 3.2 [Avoid Duplicate Serialization in RSC Props](#32-avoid-duplicate-serialization-in-rsc-props) - 3.3 [Avoid Shared Module State for Request Data](#33-avoid-shared-module-state-for-request-data) - 3.4 [Cross-Request LRU Caching](#34-cross-request-lru-caching) - 3.5 [Hoist Static I/O to Module Level](#35-hoist-static-io-to-module-level) - 3.6 [Minimize Serialization at RSC Boundaries](#36-minimize-serialization-at-rsc-boundaries) - 3.7 [Parallel Data Fetching with Component Composition](#37-parallel-data-fetching-with-component-composition) - 3.8 [Parallel Nested Data Fetching](#38-parallel-nested-data-fetching) - 3.9 [Per-Request Deduplication with React.cache()](#39-per-request-deduplication-with-reactcache) - 3.10 [Use after() for Non-Blocking Operations](#310-use-after-for-non-blocking-operations) 4. [Client-Side Data Fetching](#4-client-side-data-fetching) — **MEDIUM-HIGH** - 4.1 [Deduplicate Global Event Listeners](#41-deduplicate-global-event-listeners) - 4.2 [Use Passive Event Listeners for Scrolling Performance](#42-use-passive-event-listeners-for-scrolling-performance) - 4.3 [Use SWR for Automatic Deduplication](#43-use-swr-for-automatic-deduplication) - 4.4 [Version and Minimize localStorage Data](#44-version-and-minimize-localstorage-data) 5. [Re-render Optimization](#5-re-render-optimization) — **MEDIUM** - 5.1 [Calculate Derived State During Rendering](#51-calculate-derived-state-during-rendering) - 5.2 [Defer State Reads to Usage Point](#52-defer-state-reads-to-usage-point) - 5.3 [Do not wrap a simple expression with a primitive result type in useMemo](#53-do-not-wrap-a-simple-expression-with-a-primitive-result-type-in-usememo) - 5.4 [Don't Define Components Inside Components](#54-dont-define-components-inside-components) - 5.5 [Extract Default Non-primitive Parameter Value from Memoized Component to Constant](#55-extract-default-non-primitive-parameter-value-from-memoized-component-to-constant) - 5.6 [Extract to Memoized Components](#56-extract-to-memoized-components) - 5.7 [Narrow Effect Dependencies](#57-narrow-effect-dependencies) - 5.8 [Put Interaction Logic in Event Handlers](#58-put-interaction-logic-in-event-handlers) - 5.9 [Split Combined Hook Computations](#59-split-combined-hook-computations) - 5.10 [Subscribe to Derived State](#510-subscribe-to-derived-state) - 5.11 [Use Functional setState Updates](#511-use-functional-setstate-updates) - 5.12 [Use Lazy State Initialization](#512-use-lazy-state-initialization) - 5.13 [Use Transitions for Non-Urgent Updates](#513-use-transitions-for-non-urgent-updates) - 5.14 [Use useDeferredValue for Expensive Derived Renders](#514-use-usedeferredvalue-for-expensive-derived-renders) - 5.15 [Use useRef for Transient Values](#515-use-useref-for-transient-values) 6. [Rendering Performance](#6-rendering-performance) — **MEDIUM** - 6.1 [Animate SVG Wrapper Instead of SVG Element](#61-animate-svg-wrapper-instead-of-svg-element) - 6.2 [CSS content-visibility for Long Lists](#62-css-content-visibility-for-long-lists) - 6.3 [Hoist Static JSX Elements](#63-hoist-static-jsx-elements) - 6.4 [Optimize SVG Precision](#64-optimize-svg-precision) - 6.5 [Prevent Hydration Mismatch Without Flickering](#65-prevent-hydration-mismatch-without-flickering) - 6.6 [Suppress Expected Hydration Mismatches](#66-suppress-expected-hydration-mismatches) - 6.7 [Use Activity Component for Show/Hide](#67-use-activity-component-for-showhide) - 6.8 [Use defer or async on Script Tags](#68-use-defer-or-async-on-script-tags) - 6.9 [Use Explicit Conditional Rendering](#69-use-explicit-conditional-rendering) - 6.10 [Use React DOM Resource Hints](#610-use-react-dom-resource-hints) - 6.11 [Use useTransition Over Manual Loading States](#611-use-usetransition-over-manual-loading-states) 7. [JavaScript Performance](#7-javascript-performance) — **LOW-MEDIUM** - 7.1 [Avoid Layout Thrashing](#71-avoid-layout-thrashing) - 7.2 [Build Index Maps for Repeated Lookups](#72-build-index-maps-for-repeated-lookups) - 7.3 [Cache Property Access in Loops](#73-cache-property-access-in-loops) - 7.4 [Cache Repeated Function Calls](#74-cache-repeated-function-calls) - 7.5 [Cache Storage API Calls](#75-cache-storage-api-calls) - 7.6 [Combine Multiple Array Iterations](#76-combine-multiple-array-iterations) - 7.7 [Defer Non-Critical Work with requestIdleCallback](#77-defer-non-critical-work-with-requestidlecallback) - 7.8 [Early Length Check for Array Comparisons](#78-early-length-check-for-array-comparisons) - 7.9 [Early Return from Functions](#79-early-return-from-functions) - 7.10 [Hoist RegExp Creation](#710-hoist-regexp-creation) - 7.11 [Use flatMap to Map and Filter in One Pass](#711-use-flatmap-to-map-and-filter-in-one-pass) - 7.12 [Use Loop for Min/Max Instead of Sort](#712-use-loop-for-minmax-instead-of-sort) - 7.13 [Use Set/Map for O(1) Lookups](#713-use-setmap-for-o1-lookups) - 7.14 [Use toSorted() Instead of sort() for Immutability](#714-use-tosorted-instead-of-sort-for-immutability) 8. [Advanced Patterns](#8-advanced-patterns) — **LOW** - 8.1 [Do Not Put Effect Events in Dependency Arrays](#81-do-not-put-effect-events-in-dependency-arrays) - 8.2 [Initialize App Once, Not Per Mount](#82-initialize-app-once-not-per-mount) - 8.3 [Store Event Handlers in Refs](#83-store-event-handlers-in-refs) - 8.4 [useEffectEvent for Stable Callback Refs](#84-useeffectevent-for-stable-callback-refs) --- ## 1. Eliminating Waterfalls **Impact: CRITICAL** Waterfalls are the #1 performance killer. Each sequential await adds full network latency. Eliminating them yields the largest gains. ### 1.1 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. ### 1.2 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). ### 1.3 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:** ```typescript const userPromise = fetchUser() const profilePromise = userPromise.then(user => fetchProfile(user.id)) const [user, config, profile] = await Promise.all([ userPromise, fetchConfig(), profilePromise ]) ``` We can also create all the promises first, and do `Promise.all()` at the end. Reference: [https://github.com/shuding/better-all](https://github.com/shuding/better-all) ### 1.4 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). ### 1.5 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() ]) ``` ### 1.6 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 ( <div> <div>Sidebar</div> <div>Header</div> <div> <DataDisplay data={data} /> </div> <div>Footer</div> </div> ) } ``` 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 ( <div> <div>Sidebar</div> <div>Header</div> <div> <Suspense fallback={<Skeleton />}> <DataDisplay /> </Suspense> </div> <div>Footer</div> </div> ) } async function DataDisplay() { const data = await fetchData() // Only blocks this component return <div>{data.content}</div> } ``` Sidebar, Header, and Footer render immediately. Only DataDisplay waits for data. **Alterna - skills/react-best-practices/metadata.json (921 bytes)
{ "version": "1.0.0", "organization": "Vercel Engineering", "date": "January 2026", "abstract": "Comprehensive performance optimization guide for React and Next.js applications, designed for AI agents and LLMs. Contains 40+ rules across 8 categories, prioritized by impact from critical (eliminating waterfalls, reducing bundle size) to incremental (advanced patterns). Each rule includes detailed explanations, real-world examples comparing incorrect vs. correct implementations, and specific impact metrics to guide automated refactoring and code generation.", "references": [ "https://react.dev", "https://nextjs.org", "https://swr.vercel.app", "https://github.com/shuding/better-all", "https://github.com/isaacs/node-lru-cache", "https://vercel.com/blog/how-we-optimized-package-imports-in-next-js", "https://vercel.com/blog/how-we-made-the-vercel-dashboard-twice-as-fast" ] } - skills/react-best-practices/README.md (3360 bytes)
# React Best Practices A structured repository for creating and maintaining React Best Practices optimized for agents and LLMs. ## Structure - `rules/` - Individual rule files (one per rule) - `_sections.md` - Section metadata (titles, impacts, descriptions) - `_template.md` - Template for creating new rules - `area-description.md` - Individual rule files - `src/` - Build scripts and utilities - `metadata.json` - Document metadata (version, organization, abstract) - __`AGENTS.md`__ - Compiled output (generated) - __`test-cases.json`__ - Test cases for LLM evaluation (generated) ## Getting Started 1. Install dependencies: ```bash pnpm install ``` 2. Build AGENTS.md from rules: ```bash pnpm build ``` 3. Validate rule files: ```bash pnpm validate ``` 4. Extract test cases: ```bash pnpm extract-tests ``` ## Creating a New Rule 1. Copy `rules/_template.md` to `rules/area-description.md` 2. Choose the appropriate area prefix: - `async-` for Eliminating Waterfalls (Section 1) - `bundle-` for Bundle Size Optimization (Section 2) - `server-` for Server-Side Performance (Section 3) - `client-` for Client-Side Data Fetching (Section 4) - `rerender-` for Re-render Optimization (Section 5) - `rendering-` for Rendering Performance (Section 6) - `js-` for JavaScript Performance (Section 7) - `advanced-` for Advanced Patterns (Section 8) 3. Fill in the frontmatter and content 4. Ensure you have clear examples with explanations 5. Run `pnpm build` to regenerate AGENTS.md and test-cases.json ## Rule File Structure Each rule file should follow this structure: ```markdown --- title: Rule Title Here impact: MEDIUM impactDescription: Optional description tags: tag1, tag2, tag3 --- ## Rule Title Here Brief explanation of the rule and why it matters. **Incorrect (description of what's wrong):** ```typescript // Bad code example ``` **Correct (description of what's right):** ```typescript // Good code example ``` Optional explanatory text after examples. Reference: [Link](https://example.com) ## File Naming Convention - Files starting with `_` are special (excluded from build) - Rule files: `area-description.md` (e.g., `async-parallel.md`) - Section is automatically inferred from filename prefix - Rules are sorted alphabetically by title within each section - IDs (e.g., 1.1, 1.2) are auto-generated during build ## Impact Levels - `CRITICAL` - Highest priority, major performance gains - `HIGH` - Significant performance improvements - `MEDIUM-HIGH` - Moderate-high gains - `MEDIUM` - Moderate performance improvements - `LOW-MEDIUM` - Low-medium gains - `LOW` - Incremental improvements ## Scripts - `pnpm build` - Compile rules into AGENTS.md - `pnpm validate` - Validate all rule files - `pnpm extract-tests` - Extract test cases for LLM evaluation - `pnpm dev` - Build and validate ## Contributing When adding or modifying rules: 1. Use the correct filename prefix for your section 2. Follow the `_template.md` structure 3. Include clear bad/good examples with explanations 4. Add appropriate tags 5. Run `pnpm build` to regenerate AGENTS.md and test-cases.json 6. Rules are automatically sorted by title - no need to manage numbers! ## Acknowledgments Originally created by [@shuding](https://x.com/shuding) at [Vercel](https://vercel.com).
- skills/react-best-practices/rules/_sections.md (1554 bytes)
# Sections This file defines all sections, their ordering, impact levels, and descriptions. The section ID (in parentheses) is the filename prefix used to group rules. --- ## 1. Eliminating Waterfalls (async) **Impact:** CRITICAL **Description:** Waterfalls are the #1 performance killer. Each sequential await adds full network latency. Eliminating them yields the largest gains. ## 2. Bundle Size Optimization (bundle) **Impact:** CRITICAL **Description:** Reducing initial bundle size improves Time to Interactive and Largest Contentful Paint. ## 3. Server-Side Performance (server) **Impact:** HIGH **Description:** Optimizing server-side rendering and data fetching eliminates server-side waterfalls and reduces response times. ## 4. Client-Side Data Fetching (client) **Impact:** MEDIUM-HIGH **Description:** Automatic deduplication and efficient data fetching patterns reduce redundant network requests. ## 5. Re-render Optimization (rerender) **Impact:** MEDIUM **Description:** Reducing unnecessary re-renders minimizes wasted computation and improves UI responsiveness. ## 6. Rendering Performance (rendering) **Impact:** MEDIUM **Description:** Optimizing the rendering process reduces the work the browser needs to do. ## 7. JavaScript Performance (js) **Impact:** LOW-MEDIUM **Description:** Micro-optimizations for hot paths can add up to meaningful improvements. ## 8. Advanced Patterns (advanced) **Impact:** LOW **Description:** Advanced patterns for specific cases that require careful implementation.
- skills/react-best-practices/rules/_template.md (631 bytes)
--- title: Rule Title Here impact: MEDIUM impactDescription: Optional description of impact (e.g., "20-50% improvement") tags: tag1, tag2 --- ## Rule Title Here **Impact: MEDIUM (optional impact description)** Brief explanation of the rule and why it matters. This should be clear and concise, explaining the performance implications. **Incorrect (description of what's wrong):** ```typescript // Bad code example here const bad = example() ``` **Correct (description of what's right):** ```typescript // Good code example here const good = example() ``` Reference: [Link to documentation or resource](https://example.com)
- skills/react-best-practices/rules/advanced-effect-event-deps.md (1802 bytes)
--- 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) - skills/react-best-practices/rules/advanced-event-handler-refs.md (1483 bytes)
--- 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: it creates a stable function reference that always calls the latest version of the handler. - skills/react-best-practices/rules/advanced-init-once.md (958 bytes)
--- 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) - skills/react-best-practices/rules/advanced-use-latest.md (1072 bytes)
--- title: useEffectEvent for Stable Callback Refs impact: LOW impactDescription: prevents effect re-runs tags: advanced, hooks, useEffectEvent, refs, optimization --- ## useEffectEvent for Stable Callback Refs 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]) } ``` - skills/react-best-practices/rules/async-api-routes.md (1125 bytes)
--- 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() 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). - skills/react-best-practices/rules/async-cheap-condition-before-await.md (1220 bytes)
--- 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. - skills/react-best-practices/rules/async-defer-await.md (2208 bytes)
--- 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). - skills/react-best-practices/rules/async-dependencies.md (1293 bytes)
--- 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) - skills/react-best-practices/rules/async-parallel.md (654 bytes)
--- 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() ]) ```
- skills/react-best-practices/rules/async-suspense-boundaries.md (2510 bytes)
--- 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 ( <div> <div>Sidebar</div> <div>Header</div> <div> <DataDisplay data={data} /> </div> <div>Footer</div> </div> ) } ``` 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 ( <div> <div>Sidebar</div> <div>Header</div> <div> <Suspense fallback={<Skeleton />}> <DataDisplay /> </Suspense> </div> <div>Footer</div> </div> ) } async function DataDisplay() { const data = await fetchData() // Only blocks this component return <div>{data.content}</div> } ``` 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 ( <div> <div>Sidebar</div> <div>Header</div> <Suspense fallback={<Skeleton />}> <DataDisplay dataPromise={dataPromise} /> <DataSummary dataPromise={dataPromise} /> </Suspense> <div>Footer</div> </div> ) } function DataDisplay({ dataPromise }: { dataPromise: Promise<Data> }) { const data = use(dataPromise) // Unwraps the promise return <div>{data.content}</div> } function DataSummary({ dataPromise }: { dataPromise: Promise<Data> }) { const data = use(dataPromise) // Reuses the same promise return <div>{data.summary}</div> } ``` 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. - skills/react-best-practices/rules/bundle-analyzable-paths.md (2382 bytes)
--- 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/) - skills/react-best-practices/rules/bundle-barrel-imports.md (2795 bytes)
--- 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) - skills/react-best-practices/rules/bundle-conditional.md (949 bytes)
--- 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<React.SetStateAction<boolean>> }) { const [frames, setFrames] = useState<Frame[] | null>(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 <Skeleton /> return <Canvas frames={frames} /> } ``` The `typeof window !== 'undefined'` check prevents bundling this module for SSR, optimizing server bundle size and build speed. - skills/react-best-practices/rules/bundle-defer-third-party.md (920 bytes)
--- 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 ( <html> <body> {children} <Analytics /> </body> </html> ) } ``` **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 ( <html> <body> {children} <Analytics /> </body> </html> ) } ``` - skills/react-best-practices/rules/bundle-dynamic-imports.md (791 bytes)
--- 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 <MonacoEditor value={code} /> } ``` **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 <MonacoEditor value={code} /> } ``` - skills/react-best-practices/rules/bundle-preload.md (1149 bytes)
--- 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 }) { const preload = () => { if (typeof window !== 'undefined') { void import('./monaco-editor') } } return ( <button onMouseEnter={preload} onFocus={preload} onClick={onClick} > Open Editor </button> ) } ``` **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 <FlagsContext.Provider value={flags}> {children} </FlagsContext.Provider> } ``` The `typeof window !== 'undefined'` check prevents bundling preloaded modules for SSR, optimizing server bundle size and build speed. - skills/react-best-practices/rules/client-event-listeners.md (1969 bytes)
--- 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<string, Set<() => 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', () => { /* ... */ }) // ... } ``` - skills/react-best-practices/rules/client-localstorage-schema.md (1950 bytes)
--- 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. - skills/react-best-practices/rules/client-passive-event-listeners.md (1644 bytes)
--- 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()`. - skills/react-best-practices/rules/client-swr-dedup.md (1159 bytes)
--- 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 <button onClick={() => trigger()}>Update</button> } ``` Reference: [https://swr.vercel.app](https://swr.vercel.app) - skills/react-best-practices/rules/js-batch-dom-css.md (3266 bytes)
--- 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<HTMLDivElement>(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 <div ref={ref}>Content</div> } // Correct: toggle class function Box({ isHighlighted }: { isHighlighted: boolean }) { return ( <div className={isHighlighted ? 'highlighted-box' : ''}> Content </div> ) } ``` 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. - skills/react-best-practices/rules/js-cache-function-results.md (1949 bytes)
--- 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 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 ( <div> {projects.map(project => { // slugify() called 100+ times for same project names const slug = slugify(project.name) return <ProjectCard key={project.id} slug={slug} /> })} </div> ) } ``` **Correct (cached results):** ```typescript // Module-level cache const slugifyCache = new Map<string, string>() 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 ( <div> {projects.map(project => { // Computed only once per unique project name const slug = cachedSlugify(project.name) return <ProjectCard key={project.id} slug={slug} /> })} </div> ) } ``` **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) - skills/react-best-practices/rules/js-cache-property-access.md (532 bytes)
--- 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) } ``` - skills/react-best-practices/rules/js-cache-storage.md (1651 bytes)
--- 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<string, string | null>() 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<string, string> | 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() } }) ``` - skills/react-best-practices/rules/js-combine-iterations.md (753 bytes)
--- 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) } ``` - skills/react-best-practices/rules/js-early-exit.md (1133 bytes)
--- 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 } } ``` - skills/react-best-practices/rules/js-flatmap-filter.md (1411 bytes)
--- 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 - skills/react-best-practices/rules/js-hoist-regexp.md (1028 bytes)
--- 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 ``` - skills/react-best-practices/rules/js-index-maps.md (837 bytes)
--- 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. - skills/react-best-practices/rules/js-length-check-first.md (1747 bytes)
--- 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 - skills/react-best-practices/rules/js-min-max-loop.md (2290 bytes)
--- 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. - skills/react-best-practices/rules/js-request-idle-callback.md (2647 bytes)
--- 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 - skills/react-best-practices/rules/js-set-map-lookups.md (532 bytes)
--- 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)) ```
- skills/react-best-practices/SKILL.md (7251 bytes)
--- name: vercel-react-best-practices description: React and Next.js performance optimization guidelines from Vercel Engineering. This skill should be used when writing, reviewing, or refactoring React/Next.js code to ensure optimal performance patterns. Triggers on tasks involving React components, Next.js pages, data fetching, bundle optimization, or performance improvements. license: MIT metadata: author: vercel version: "1.0.0" --- # Vercel React Best Practices Comprehensive performance optimization guide for React and Next.js applications, maintained by Vercel. Contains 70 rules across 8 categories, prioritized by impact to guide automated refactoring and code generation. ## When to Apply Reference these guidelines when: - Writing new React components or Next.js pages - Implementing data fetching (client or server-side) - Reviewing code for performance issues - Refactoring existing React/Next.js code - Optimizing bundle size or load times ## Rule Categories by Priority | Priority | Category | Impact | Prefix | |----------|----------|--------|--------| | 1 | Eliminating Waterfalls | CRITICAL | `async-` | | 2 | Bundle Size Optimization | CRITICAL | `bundle-` | | 3 | Server-Side Performance | HIGH | `server-` | | 4 | Client-Side Data Fetching | MEDIUM-HIGH | `client-` | | 5 | Re-render Optimization | MEDIUM | `rerender-` | | 6 | Rendering Performance | MEDIUM | `rendering-` | | 7 | JavaScript Performance | LOW-MEDIUM | `js-` | | 8 | Advanced Patterns | LOW | `advanced-` | ## Quick Reference ### 1. Eliminating Waterfalls (CRITICAL) - `async-cheap-condition-before-await` - Check cheap sync conditions before awaiting flags or remote values - `async-defer-await` - Move await into branches where actually used - `async-parallel` - Use Promise.all() for independent operations - `async-dependencies` - Use better-all for partial dependencies - `async-api-routes` - Start promises early, await late in API routes - `async-suspense-boundaries` - Use Suspense to stream content ### 2. Bundle Size Optimization (CRITICAL) - `bundle-barrel-imports` - Import directly, avoid barrel files - `bundle-analyzable-paths` - Prefer statically analyzable import and file-system paths to avoid broad bundles and traces - `bundle-dynamic-imports` - Use next/dynamic for heavy components - `bundle-defer-third-party` - Load analytics/logging after hydration - `bundle-conditional` - Load modules only when feature is activated - `bundle-preload` - Preload on hover/focus for perceived speed ### 3. Server-Side Performance (HIGH) - `server-auth-actions` - Authenticate server actions like API routes - `server-cache-react` - Use React.cache() for per-request deduplication - `server-cache-lru` - Use LRU cache for cross-request caching - `server-dedup-props` - Avoid duplicate serialization in RSC props - `server-hoist-static-io` - Hoist static I/O (fonts, logos) to module level - `server-no-shared-module-state` - Avoid module-level mutable request state in RSC/SSR - `server-serialization` - Minimize data passed to client components - `server-parallel-fetching` - Restructure components to parallelize fetches - `server-parallel-nested-fetching` - Chain nested fetches per item in Promise.all - `server-after-nonblocking` - Use after() for non-blocking operations ### 4. Client-Side Data Fetching (MEDIUM-HIGH) - `client-swr-dedup` - Use SWR for automatic request deduplication - `client-event-listeners` - Deduplicate global event listeners - `client-passive-event-listeners` - Use passive listeners for scroll - `client-localstorage-schema` - Version and minimize localStorage data ### 5. Re-render Optimization (MEDIUM) - `rerender-defer-reads` - Don't subscribe to state only used in callbacks - `rerender-memo` - Extract expensive work into memoized components - `rerender-memo-with-default-value` - Hoist default non-primitive props - `rerender-dependencies` - Use primitive dependencies in effects - `rerender-derived-state` - Subscribe to derived booleans, not raw values - `rerender-derived-state-no-effect` - Derive state during render, not effects - `rerender-functional-setstate` - Use functional setState for stable callbacks - `rerender-lazy-state-init` - Pass function to useState for expensive values - `rerender-simple-expression-in-memo` - Avoid memo for simple primitives - `rerender-split-combined-hooks` - Split hooks with independent dependencies - `rerender-move-effect-to-event` - Put interaction logic in event handlers - `rerender-transitions` - Use startTransition for non-urgent updates - `rerender-use-deferred-value` - Defer expensive renders to keep input responsive - `rerender-use-ref-transient-values` - Use refs for transient frequent values - `rerender-no-inline-components` - Don't define components inside components ### 6. Rendering Performance (MEDIUM) - `rendering-animate-svg-wrapper` - Animate div wrapper, not SVG element - `rendering-content-visibility` - Use content-visibility for long lists - `rendering-hoist-jsx` - Extract static JSX outside components - `rendering-svg-precision` - Reduce SVG coordinate precision - `rendering-hydration-no-flicker` - Use inline script for client-only data - `rendering-hydration-suppress-warning` - Suppress expected mismatches - `rendering-activity` - Use Activity component for show/hide - `rendering-conditional-render` - Use ternary, not && for conditionals - `rendering-usetransition-loading` - Prefer useTransition for loading state - `rendering-resource-hints` - Use React DOM resource hints for preloading - `rendering-script-defer-async` - Use defer or async on script tags ### 7. JavaScript Performance (LOW-MEDIUM) - `js-batch-dom-css` - Group CSS changes via classes or cssText - `js-index-maps` - Build Map for repeated lookups - `js-cache-property-access` - Cache object properties in loops - `js-cache-function-results` - Cache function results in module-level Map - `js-cache-storage` - Cache localStorage/sessionStorage reads - `js-combine-iterations` - Combine multiple filter/map into one loop - `js-length-check-first` - Check array length before expensive comparison - `js-early-exit` - Return early from functions - `js-hoist-regexp` - Hoist RegExp creation outside loops - `js-min-max-loop` - Use loop for min/max instead of sort - `js-set-map-lookups` - Use Set/Map for O(1) lookups - `js-tosorted-immutable` - Use toSorted() for immutability - `js-flatmap-filter` - Use flatMap to map and filter in one pass - `js-request-idle-callback` - Defer non-critical work to browser idle time ### 8. Advanced Patterns (LOW) - `advanced-effect-event-deps` - Don't put `useEffectEvent` results in effect deps - `advanced-event-handler-refs` - Store event handlers in refs - `advanced-init-once` - Initialize app once per app load - `advanced-use-latest` - useLatest for stable callback refs ## How to Use Read individual rule files for detailed explanations and code examples: ``` rules/async-parallel.md rules/bundle-barrel-imports.md ``` Each rule file contains: - Brief explanation of why it matters - Incorrect code example with explanation - Correct code example with explanation - Additional context and references ## Full Compiled Document For the complete guide with all rules expanded: `AGENTS.md`
- skills/react-native-skills/AGENTS.md (73771 bytes)
# React Native Skills **Version 1.0.0** Engineering January 2026 > **Note:** > This document is mainly for agents and LLMs to follow when maintaining, > generating, or refactoring React Native codebases. Humans > may also find it useful, but guidance here is optimized for automation > and consistency by AI-assisted workflows. --- ## Abstract Comprehensive performance optimization guide for React Native applications, designed for AI agents and LLMs. Contains 35+ rules across 13 categories, prioritized by impact from critical (core rendering, list performance) to incremental (fonts, imports). Each rule includes detailed explanations, real-world examples comparing incorrect vs. correct implementations, and specific impact metrics to guide automated refactoring and code generation. --- ## Table of Contents 1. [Core Rendering](#1-core-rendering) — **CRITICAL** - 1.1 [Never Use && with Potentially Falsy Values](#11-never-use--with-potentially-falsy-values) - 1.2 [Wrap Strings in Text Components](#12-wrap-strings-in-text-components) 2. [List Performance](#2-list-performance) — **HIGH** - 2.1 [Avoid Inline Objects in renderItem](#21-avoid-inline-objects-in-renderitem) - 2.2 [Hoist callbacks to the root of lists](#22-hoist-callbacks-to-the-root-of-lists) - 2.3 [Keep List Items Lightweight](#23-keep-list-items-lightweight) - 2.4 [Optimize List Performance with Stable Object References](#24-optimize-list-performance-with-stable-object-references) - 2.5 [Pass Primitives to List Items for Memoization](#25-pass-primitives-to-list-items-for-memoization) - 2.6 [Use a List Virtualizer for Any List](#26-use-a-list-virtualizer-for-any-list) - 2.7 [Use Compressed Images in Lists](#27-use-compressed-images-in-lists) - 2.8 [Use Item Types for Heterogeneous Lists](#28-use-item-types-for-heterogeneous-lists) 3. [Animation](#3-animation) — **HIGH** - 3.1 [Animate Transform and Opacity Instead of Layout Properties](#31-animate-transform-and-opacity-instead-of-layout-properties) - 3.2 [Prefer useDerivedValue Over useAnimatedReaction](#32-prefer-usederivedvalue-over-useanimatedreaction) - 3.3 [Use GestureDetector for Animated Press States](#33-use-gesturedetector-for-animated-press-states) 4. [Scroll Performance](#4-scroll-performance) — **HIGH** - 4.1 [Never Track Scroll Position in useState](#41-never-track-scroll-position-in-usestate) 5. [Navigation](#5-navigation) — **HIGH** - 5.1 [Use Native Navigators for Navigation](#51-use-native-navigators-for-navigation) 6. [React State](#6-react-state) — **MEDIUM** - 6.1 [Minimize State Variables and Derive Values](#61-minimize-state-variables-and-derive-values) - 6.2 [Use fallback state instead of initialState](#62-use-fallback-state-instead-of-initialstate) - 6.3 [useState Dispatch updaters for State That Depends on Current Value](#63-usestate-dispatch-updaters-for-state-that-depends-on-current-value) 7. [State Architecture](#7-state-architecture) — **MEDIUM** - 7.1 [State Must Represent Ground Truth](#71-state-must-represent-ground-truth) 8. [React Compiler](#8-react-compiler) — **MEDIUM** - 8.1 [Destructure Functions Early in Render (React Compiler)](#81-destructure-functions-early-in-render-react-compiler) - 8.2 [Use .get() and .set() for Reanimated Shared Values (not .value)](#82-use-get-and-set-for-reanimated-shared-values-not-value) 9. [User Interface](#9-user-interface) — **MEDIUM** - 9.1 [Measuring View Dimensions](#91-measuring-view-dimensions) - 9.2 [Modern React Native Styling Patterns](#92-modern-react-native-styling-patterns) - 9.3 [Use contentInset for Dynamic ScrollView Spacing](#93-use-contentinset-for-dynamic-scrollview-spacing) - 9.4 [Use contentInsetAdjustmentBehavior for Safe Areas](#94-use-contentinsetadjustmentbehavior-for-safe-areas) - 9.5 [Use expo-image for Optimized Images](#95-use-expo-image-for-optimized-images) - 9.6 [Use Galeria for Image Galleries and Lightbox](#96-use-galeria-for-image-galleries-and-lightbox) - 9.7 [Use Native Menus for Dropdowns and Context Menus](#97-use-native-menus-for-dropdowns-and-context-menus) - 9.8 [Use Native Modals Over JS-Based Bottom Sheets](#98-use-native-modals-over-js-based-bottom-sheets) - 9.9 [Use Pressable Instead of Touchable Components](#99-use-pressable-instead-of-touchable-components) 10. [Design System](#10-design-system) — **MEDIUM** - 10.1 [Use Compound Components Over Polymorphic Children](#101-use-compound-components-over-polymorphic-children) 11. [Monorepo](#11-monorepo) — **LOW** - 11.1 [Install Native Dependencies in App Directory](#111-install-native-dependencies-in-app-directory) - 11.2 [Use Single Dependency Versions Across Monorepo](#112-use-single-dependency-versions-across-monorepo) 12. [Third-Party Dependencies](#12-third-party-dependencies) — **LOW** - 12.1 [Import from Design System Folder](#121-import-from-design-system-folder) 13. [JavaScript](#13-javascript) — **LOW** - 13.1 [Hoist Intl Formatter Creation](#131-hoist-intl-formatter-creation) 14. [Fonts](#14-fonts) — **LOW** - 14.1 [Load fonts natively at build time](#141-load-fonts-natively-at-build-time) --- ## 1. Core Rendering **Impact: CRITICAL** Fundamental React Native rendering rules. Violations cause runtime crashes or broken UI. ### 1.1 Never Use && with Potentially Falsy Values **Impact: CRITICAL (prevents production crash)** Never use `{value && <Component />}` when `value` could be an empty string or `0`. These are falsy but JSX-renderable—React Native will try to render them as text outside a `<Text>` component, causing a hard crash in production. **Incorrect: crashes if count is 0 or name is ""** ```tsx function Profile({ name, count }: { name: string; count: number }) { return ( <View> {name && <Text>{name}</Text>} {count && <Text>{count} items</Text>} </View> ) } // If name="" or count=0, renders the falsy value → crash ``` **Correct: ternary with null** ```tsx function Profile({ name, count }: { name: string; count: number }) { return ( <View> {name ? <Text>{name}</Text> : null} {count ? <Text>{count} items</Text> : null} </View> ) } ``` **Correct: explicit boolean coercion** ```tsx function Profile({ name, count }: { name: string; count: number }) { return ( <View> {!!name && <Text>{name}</Text>} {!!count && <Text>{count} items</Text>} </View> ) } ``` **Best: early return** ```tsx function Profile({ name, count }: { name: string; count: number }) { if (!name) return null return ( <View> <Text>{name}</Text> {count > 0 ? <Text>{count} items</Text> : null} </View> ) } ``` Early returns are clearest. When using conditionals inline, prefer ternary or explicit boolean checks. **Lint rule:** Enable `react/jsx-no-leaked-render` from [eslint-plugin-react](https://github.com/jsx-eslint/eslint-plugin-react/blob/master/docs/rules/jsx-no-leaked-render.md) to catch this automatically. ### 1.2 Wrap Strings in Text Components **Impact: CRITICAL (prevents runtime crash)** Strings must be rendered inside `<Text>`. React Native crashes if a string is a direct child of `<View>`. **Incorrect: crashes** ```tsx import { View } from 'react-native' function Greeting({ name }: { name: string }) { return <View>Hello, {name}!</View> } // Error: Text strings must be rendered within a <Text> component. ``` **Correct:** ```tsx import { View, Text } from 'react-native' function Greeting({ name }: { name: string }) { return ( <View> <Text>Hello, {name}!</Text> </View> ) } ``` --- ## 2. List Performance **Impact: HIGH** Optimizing virtualized lists (FlatList, LegendList, FlashList) for smooth scrolling and fast updates. ### 2.1 Avoid Inline Objects in renderItem **Impact: HIGH (prevents unnecessary re-renders of memoized list items)** Don't create new objects inside `renderItem` to pass as props. Inline objects create new references on every render, breaking memoization. Pass primitive values directly from `item` instead. **Incorrect: inline object breaks memoization** ```tsx function UserList({ users }: { users: User[] }) { return ( <LegendList data={users} renderItem={({ item }) => ( <UserRow // Bad: new object on every render user={{ id: item.id, name: item.name, avatar: item.avatar }} /> )} /> ) } ``` **Incorrect: inline style object** ```tsx renderItem={({ item }) => ( <UserRow name={item.name} // Bad: new style object on every render style={{ backgroundColor: item.isActive ? 'green' : 'gray' }} /> )} ``` **Correct: pass item directly or primitives** ```tsx function UserList({ users }: { users: User[] }) { return ( <LegendList data={users} renderItem={({ item }) => ( // Good: pass the item directly <UserRow user={item} /> )} /> ) } ``` **Correct: pass primitives, derive inside child** ```tsx renderItem={({ item }) => ( <UserRow id={item.id} name={item.name} isActive={item.isActive} /> )} const UserRow = memo(function UserRow({ id, name, isActive }: Props) { // Good: derive style inside memoized component const backgroundColor = isActive ? 'green' : 'gray' return <View style={[styles.row, { backgroundColor }]}>{/* ... */}</View> }) ``` **Correct: hoist static styles in module scope** ```tsx const activeStyle = { backgroundColor: 'green' } const inactiveStyle = { backgroundColor: 'gray' } renderItem={({ item }) => ( <UserRow name={item.name} // Good: stable references style={item.isActive ? activeStyle : inactiveStyle} /> )} ``` Passing primitives or stable references allows `memo()` to skip re-renders when the actual values haven't changed. **Note:** If you have the React Compiler enabled, it handles memoization automatically and these manual optimizations become less critical. ### 2.2 Hoist callbacks to the root of lists **Impact: MEDIUM (Fewer re-renders and faster lists)** When passing callback functions to list items, create a single instance of the callback at the root of the list. Items should then call it with a unique identifier. **Incorrect: creates a new callback on each render** ```typescript return ( <LegendList renderItem={({ item }) => { // bad: creates a new callback on each render const onPress = () => handlePress(item.id) return <Item key={item.id} item={item} onPress={onPress} /> }} /> ) ``` **Correct: a single function instance passed to each item** ```typescript const onPress = useCallback(() => handlePress(item.id), [handlePress, item.id]) return ( <LegendList renderItem={({ item }) => ( <Item key={item.id} item={item} onPress={onPress} /> )} /> ) ``` Reference: [https://example.com](https://example.com) ### 2.3 Keep List Items Lightweight **Impact: HIGH (reduces render time for visible items during scroll)** List items should be as inexpensive as possible to render. Minimize hooks, avoid queries, and limit React Context access. Virtualized lists render many items during scroll—expensive items cause jank. **Incorrect: heavy list item** ```tsx function ProductRow({ id }: { id: string }) { // Bad: query inside list item const { data: product } = useQuery(['product', id], () => fetchProduct(id)) // Bad: multiple context accesses const theme = useContext(ThemeContext) const user = useContext(UserContext) const cart = useContext(CartContext) // Bad: expensive computation const recommendations = useMemo( () => computeRecommendations(product), [product] ) return <View>{/* ... */}</View> } ``` **Correct: lightweight list item** ```tsx function ProductRow({ name, price, imageUrl }: Props) { // Good: receives only primitives, minimal hooks return ( <View> <Image source={{ uri: imageUrl }} /> <Text>{name}</Text> <Text>{price}</Text> </View> ) } ``` **Move data fetching to parent:** ```tsx // Parent fetches all data once function ProductList() { const { data: products } = useQuery(['products'], fetchProducts) return ( <LegendList data={products} renderItem={({ item }) => ( <ProductRow name={item.name} price={item.price} imageUrl={item.image} /> )} /> ) } ``` **For shared values, use Zustand selectors instead of Context:** ```tsx // Incorrect: Context causes re-render when any cart value changes function ProductRow({ id, name }: Props) { const { items } = useContext(CartContext) const inCart = items.includes(id) // ... } // Correct: Zustand selector only re-renders when this specific value changes function ProductRow({ id, name }: Props) { // use Set.has (created once at the root) instead of Array.includes() const inCart = useCartStore((s) => s.items.has(id)) // ... } ``` **Guidelines for list items:** - No queries or data fetching - No expensive computations (move to parent or memoize at parent level) - Prefer Zustand selectors over React Context - Minimize useState/useEffect hooks - Pass pre-computed values as props The goal: list items should be simple rendering functions that take props and return JSX. ### 2.4 Optimize List Performance with Stable Object References **Impact: CRITICAL (virtualization relies on reference stability)** Don't map or filter data before passing to virtualized lists. Virtualization relies on object reference stability to know what changed—new references cause full re-renders of all visible items. Attempt to prevent frequent renders at the list-parent level. Where needed, use context selectors within list items. **Incorrect: creates new object references on every keystroke** ```tsx function DomainSearch() { const { keyword, setKeyword } = useKeywordZustandState() const { data: tlds } = useTlds() // Bad: creates new objects on every render, reparenting the entire list on every keystroke const domains = tlds.map((tld) => ({ domain: `${keyword}.${tld.name}`, tld: tld.name, price: tld.price, })) return ( <> <TextInput value={keyword} onChangeText={setKeyword} /> <LegendList data={domains} renderItem={({ item }) => <DomainItem item={item} keyword={keyword} />} /> </> ) } ``` **Correct: stable references, transform inside items** ```tsx const renderItem = ({ item }) => <DomainItem tld={item} /> function DomainSearch() { const { data: tlds } = useTlds() return ( <LegendList // good: as long as the data is stable, LegendList will not re-render the entire list data={tlds} renderItem={renderItem} /> ) } function DomainItem({ tld }: { tld: Tld }) { // good: transform within items, and don't pass the dynamic data as a prop // good: use a selector function from zustand to receive a stable string back const domain = useKeywordZustandState((s) => s.keyword + '.' + tld.na - skills/react-native-skills/SKILL.md (4439 bytes)
--- name: vercel-react-native-skills description: React Native and Expo best practices for building performant mobile apps. Use when building React Native components, optimizing list performance, implementing animations, or working with native modules. Triggers on tasks involving React Native, Expo, mobile performance, or native platform APIs. license: MIT metadata: author: vercel version: '1.0.0' --- # React Native Skills Comprehensive best practices for React Native and Expo applications. Contains rules across multiple categories covering performance, animations, UI patterns, and platform-specific optimizations. ## When to Apply Reference these guidelines when: - Building React Native or Expo apps - Optimizing list and scroll performance - Implementing animations with Reanimated - Working with images and media - Configuring native modules or fonts - Structuring monorepo projects with native dependencies ## Rule Categories by Priority | Priority | Category | Impact | Prefix | | -------- | ---------------- | -------- | -------------------- | | 1 | List Performance | CRITICAL | `list-performance-` | | 2 | Animation | HIGH | `animation-` | | 3 | Navigation | HIGH | `navigation-` | | 4 | UI Patterns | HIGH | `ui-` | | 5 | State Management | MEDIUM | `react-state-` | | 6 | Rendering | MEDIUM | `rendering-` | | 7 | Monorepo | MEDIUM | `monorepo-` | | 8 | Configuration | LOW | `fonts-`, `imports-` | ## Quick Reference ### 1. List Performance (CRITICAL) - `list-performance-virtualize` - Use FlashList for large lists - `list-performance-item-memo` - Memoize list item components - `list-performance-callbacks` - Stabilize callback references - `list-performance-inline-objects` - Avoid inline style objects - `list-performance-function-references` - Extract functions outside render - `list-performance-images` - Optimize images in lists - `list-performance-item-expensive` - Move expensive work outside items - `list-performance-item-types` - Use item types for heterogeneous lists ### 2. Animation (HIGH) - `animation-gpu-properties` - Animate only transform and opacity - `animation-derived-value` - Use useDerivedValue for computed animations - `animation-gesture-detector-press` - Use Gesture.Tap instead of Pressable ### 3. Navigation (HIGH) - `navigation-native-navigators` - Use native stack and native tabs over JS navigators ### 4. UI Patterns (HIGH) - `ui-expo-image` - Use expo-image for all images - `ui-image-gallery` - Use Galeria for image lightboxes - `ui-pressable` - Use Pressable over TouchableOpacity - `ui-safe-area-scroll` - Handle safe areas in ScrollViews - `ui-scrollview-content-inset` - Use contentInset for headers - `ui-menus` - Use native context menus - `ui-native-modals` - Use native modals when possible - `ui-measure-views` - Use onLayout, not measure() - `ui-styling` - Use StyleSheet.create or Nativewind ### 5. State Management (MEDIUM) - `react-state-minimize` - Minimize state subscriptions - `react-state-dispatcher` - Use dispatcher pattern for callbacks - `react-state-fallback` - Show fallback on first render - `react-compiler-destructure-functions` - Destructure for React Compiler - `react-compiler-reanimated-shared-values` - Handle shared values with compiler ### 6. Rendering (MEDIUM) - `rendering-text-in-text-component` - Wrap text in Text components - `rendering-no-falsy-and` - Avoid falsy && for conditional rendering ### 7. Monorepo (MEDIUM) - `monorepo-native-deps-in-app` - Keep native dependencies in app package - `monorepo-single-dependency-versions` - Use single versions across packages ### 8. Configuration (LOW) - `fonts-config-plugin` - Use config plugins for custom fonts - `imports-design-system-folder` - Organize design system imports - `js-hoist-intl` - Hoist Intl object creation ## How to Use Read individual rule files for detailed explanations and code examples: ``` rules/list-performance-virtualize.md rules/animation-gpu-properties.md ``` Each rule file contains: - Brief explanation of why it matters - Incorrect code example with explanation - Correct code example with explanation - Additional context and references ## Full Compiled Document For the complete guide with all rules expanded: `AGENTS.md`
- skills/react-view-transitions/AGENTS.md (59088 bytes)
# React View Transitions **Version 1.0.0** Vercel Engineering > **Note:** > This standalone guide is compiled from `SKILL.md` and its reference files > for agents that consume a single `AGENTS.md` document. Edit the source > files, not this compiled copy. --- Animate between UI states using the browser's native `document.startViewTransition`. Declare *what* with `<ViewTransition>`, trigger *when* with `startTransition` / `useDeferredValue` / `Suspense`, control *how* with CSS classes. Unsupported browsers skip animations gracefully. ## When to Animate Every `<ViewTransition>` should communicate a spatial relationship or continuity. If you can't articulate what it communicates, don't add it. Implement **all** applicable patterns from this list, in this order: | Priority | Pattern | What it communicates | |----------|---------|---------------------| | 1 | **Shared element** (`name`) | "Same thing — going deeper" | | 2 | **Suspense reveal** | "Data loaded" | | 3 | **List identity** (per-item `key`) | "Same items, new arrangement" | | 4 | **State change** (`enter`/`exit`) | "Something appeared/disappeared" | | 5 | **Route change** (page-level) | "Going to a new place" | This is an implementation order, not a "pick one" list. Implement every pattern that fits the app. Only skip a pattern if the app has no use case for it. ### Choosing Animation Style | Context | Animation | Why | |---------|-----------|-----| | Hierarchical navigation (list → detail) | Type-keyed `nav-forward` / `nav-back` | Communicates spatial depth | | Lateral navigation (tab-to-tab) | Bare `<ViewTransition>` (fade) or `default="none"` | No depth to communicate | | Suspense reveal | `enter`/`exit` string props | Content arriving | | Revalidation / background refresh | `default="none"` | Silent — no animation needed | Reserve directional slides for hierarchical navigation (list → detail) and ordered sequences (prev/next photo, carousel, paginated results). For ordered sequences, the direction communicates position: "next" slides from right, "previous" from left. Lateral/unordered navigation (tab-to-tab) should not use directional slides — it falsely implies spatial depth. --- ## Availability - **Next.js:** Do **not** install `react@canary` — the App Router already bundles React canary internally. `ViewTransition` works out of the box. `npm ls react` may show a stable-looking version; this is expected. - **Without Next.js:** Use stable `react` and `react-dom` 19.3 or newer (`ViewTransition` and `addTransitionType` became stable in React 19.3). Earlier stable React versions do not include these APIs. - Browser support: Chromium 125+ (React needs the v2 object form of `startViewTransition`), Firefox 144+, Safari 18.2+. Graceful degradation on unsupported browsers. --- ## Implementation Workflow When adding view transitions to an existing app, **follow [references/implementation.md](references/implementation.md) step by step.** Start with the audit — do not skip it. Use [references/css-recipes.md](references/css-recipes.md) for the applicable CSS and adapt it to the app. --- ## Core Concepts ### The `<ViewTransition>` Component ```jsx import { ViewTransition } from 'react'; <ViewTransition> <Component /> </ViewTransition> ``` React auto-assigns a unique `view-transition-name` and calls `document.startViewTransition` behind the scenes. Never call `startViewTransition` yourself. ### Animation Triggers | Trigger | When it fires | |---------|--------------| | **enter** | `<ViewTransition>` first inserted during a Transition | | **exit** | `<ViewTransition>` first removed during a Transition | | **update** | DOM mutations inside a `<ViewTransition>`, or the boundary itself changing size/position due to an immediate sibling. With nested VTs, mutation applies to the innermost one | | **share** | Named VT unmounts and another with same `name` mounts in the same Transition | Only `startTransition`, `useDeferredValue`, or `Suspense` activate VTs. Regular `setState` does not animate. ### Critical Placement Rule `<ViewTransition>` only activates enter/exit if it appears **before any DOM nodes**: ```jsx // Works <ViewTransition enter="auto" exit="auto"> <div>Content</div> </ViewTransition> // Broken — div wraps the VT, suppressing enter/exit <div> <ViewTransition enter="auto" exit="auto"> <div>Content</div> </ViewTransition> </div> ``` --- ## Styling with View Transition Classes ### Props Values: `"auto"` (browser cross-fade), `"none"` (disabled), `"class-name"` (custom CSS), or `{ [type]: value }` for type-specific animations. ```jsx <ViewTransition default="none" enter="slide-in" exit="slide-out" share="morph" /> ``` If `default` is `"none"`, all triggers are off unless explicitly listed. ### CSS Pseudo-Elements - `::view-transition-old(.class)` — outgoing snapshot - `::view-transition-new(.class)` — incoming snapshot - `::view-transition-group(.class)` — container - `::view-transition-image-pair(.class)` — old + new pair See [references/css-recipes.md](references/css-recipes.md) for ready-to-use animation recipes. --- ## Transition Types Tag transitions with `addTransitionType` so VTs can pick different animations based on context. Call it multiple times to stack types — different VTs in the tree react to different types: ```jsx startTransition(() => { addTransitionType('nav-forward'); addTransitionType('select-item'); router.push('/detail/1'); }); ``` Pass an object to map types to CSS classes. Works on `enter`, `exit`, **and** `share`: ```jsx <ViewTransition enter={{ 'nav-forward': 'slide-from-right', 'nav-back': 'slide-from-left', default: 'none' }} exit={{ 'nav-forward': 'slide-to-left', 'nav-back': 'slide-to-right', default: 'none' }} share={{ 'nav-forward': 'morph-forward', 'nav-back': 'morph-back', default: 'morph' }} default="none" > <Page /> </ViewTransition> ``` `enter` and `exit` don't have to be symmetric. For example, fade in but slide out directionally: ```jsx <ViewTransition enter={{ 'nav-forward': 'fade-in', 'nav-back': 'fade-in', default: 'none' }} exit={{ 'nav-forward': 'nav-forward', 'nav-back': 'nav-back', default: 'none' }} default="none" > ``` **TypeScript:** `ViewTransitionClassPerType` requires a `default` key in the object. For apps with multiple pages, extract the type-keyed VT into a reusable wrapper: ```jsx export function DirectionalTransition({ children }: { children: React.ReactNode }) { return ( <ViewTransition enter={{ 'nav-forward': 'nav-forward', 'nav-back': 'nav-back', default: 'none' }} exit={{ 'nav-forward': 'nav-forward', 'nav-back': 'nav-back', default: 'none' }} default="none" > {children} </ViewTransition> ); } ``` ### `router.back()` and Browser Back Button `router.back()` and the browser's back/forward buttons carry **no transition types**, so type-keyed animations (directional slides) resolve to their `default` and don't play — untyped shared-element morphs still apply. For typed animations, use `router.push()` with an explicit URL. ### Types and Suspense Types are available during navigation but **not** during subsequent Suspense reveals (separate transitions, no type). Use type maps for page-level enter/exit; use simple string props for Suspense reveals. ### Shared Element Readiness A shared element transition can pair elements only when both the old and new views are rendered in the same Transition. If incoming content suspends, only its fallback exists for that update; the resolved content appears in a later Suspense transition and can be animated separately. --- ## Shared Element Transitions Same `name` on two VTs — one unmounting, one mounting — creates a shared element morph: ```jsx <ViewTransition name="hero-image"> <img src="/thumb.jpg" onClick={() => startTransition(() => onSelect())} /> </ViewTransition> // On the other view — same name <ViewTransition name="hero-image"> <img src="/full.jpg" /> </ViewTransition> ``` - Only one VT with a given `name` can be mounted at a time — use unique names (`photo-${id}`). Watch for reusable components: if a component with a named VT is rendered in both a modal/popover *and* a page, both mount simultaneously and break the morph. Either make the name conditional (via a prop) or move the named VT out of the shared component into the specific consumer. - `share` takes precedence over `enter`/`exit`. Think through each navigation path: when no matching pair forms (e.g., the target page doesn't have the same name), `enter`/`exit` fires instead. Consider whether the element needs a fallback animation for those paths. - Two ways a wired-up morph silently never fires: (1) `default="none"` with no explicit `share` prop — share resolves to none; (2) type-keyed `share` where the navigation never adds the type — a plain link click resolves the map's `default`. Every link that should morph must add the type (`transitionTypes` on `next/link`, or `addTransitionType`). - Never use a fade-out exit on pages with shared morphs — use a directional slide instead. --- ## Common Patterns ### Enter/Exit ```jsx {show && ( <ViewTransition enter="fade-in" exit="fade-out"><Panel /></ViewTransition> )} ``` ### List Reorder ```jsx {items.map(item => ( <ViewTransition key={item.id}><ItemCard item={item} /></ViewTransition> ))} ``` Trigger inside `startTransition`. Avoid wrapper `<div>`s between list and VT. ### Layout Displacement Morph Only content inside an activated boundary animates position — everything else teleports to its new layout spot. Wrap the sibling content below a growing/shrinking list in a bare `<ViewTransition>` so it glides instead of jumping. See [Layout Displacement Morph](references/patterns.md#layout-displacement-morph). ### Composing Shared Elements with List Identity Shared elements and list identity are independent concerns — don't confuse one for the other. When a list item contains a shared element (e.g., an image that morphs into a detail view), use two nested `<ViewTransition>` boundaries: ```jsx {items.map(item => ( <ViewTransition key={item.id}> {/* list identity */} <Link href={`/items/${item.id}`}> <ViewTransition name={`item-image-${item.id}`} share="morph"> {/* shared element */} <Image src={item.image} /> </ViewTransition> <p>{item.name}</p> </Link> </ViewTransition> ))} ``` The outer VT handles list reorder/enter animations. The inner VT handles the cross-route shared element morph. Missing either layer means that animation silently doesn't happen. ### Force Re-Enter with `key` ```jsx <ViewTransition key={searchParams.toString()} enter="slide-up" default="none"> <ResultsGrid /> </ViewTransition> ``` **Caution:** If wrapping `<Suspense>`, changing `key` remounts the boundary and refetches. ### Suspense Fallback to Content Simple cross-fade: ```jsx <ViewTransition> <Suspense fallback={<Skeleton />}><Content /></Suspense> </ViewTransition> ``` Directional reveal: ```jsx <Suspense fallback={<ViewTransition exit="slide-down"><Skeleton /></ViewTransition>}> <ViewTransition enter="slide-up" default="none"><Content /></ViewTransition> </Suspense> ``` For more patterns, see [references/patterns.md](references/patterns.md). --- ## How Multiple VTs Interact Every VT matching the trigger fires simultaneously in a single `document.startViewTransition`. VTs in **different** transitions (navigation vs later Suspense resolve) don't compete. ### Use `default="none"` Deliberately Without it, every VT fires the browser cross-fade on **every** transition — Suspense resolves, `useDeferredValue` updates, background revalidations. Use `default="none"` on named/shared elements and type-keyed page VTs. But it also turns off `update` (layout/reflow morphs) and `share` (a named pair with no explicit `share` prop never morphs). Keyed list items and displaced siblings *want* update — leave them bare or set `update="auto"`. ### Two Patterns Coexist **Pattern A — Directional slides:** Type-keyed VT on each page, fires during navigation. **Pattern B — Suspense reveals:** Simple string props, fires when data loads (no type). They coexist because they fire at different moments. `default="none"` on both prevents cross-interference. Always pair `enter` with `exit`. Place directional VTs in page components, not layouts. ### Nested VT Limitation When a parent VT mounts/unmounts **as one unit** with nested VTs inside it, the nested ones do not fire their own enter/exit — only the outermost VT animates. (A child VT mounted inside a *persistent* parent VT fires enter/exit normally.) Per-item staggered animations during page navigation are not currently available in Next.js; see [troubleshooting](references/troubleshooting.md) for the upstream experimental status. --- ## Next.js Integration For Next.js integration (`transitionTypes` on `next/link` and `useRouter`, App Router patterns, Server Components), see [references/nextjs.md](references/nextjs.md). --- ## Accessibility Always add the reduced motion CSS from [references/css-recipes.md](references/css-recipes.md#reduced-motion) to your global stylesheet. --- ## Reference Files - **[references/implementation.md](references/implementation.md)** — Step-by-step implementation workflow. - **[references/patterns.md](references/patterns.md)** — Patterns, animation timing, and events API. - **[references/troubleshooting.md](references/troubleshooting.md)** — Symptom-driven debugging and runtime limitations. - **[references/css-recipes.md](references/css-recipes.md)** — Ready-to-use CSS animation recipes. - **[references/nextjs.md](references/nextjs.md)** — Next.js App Router patterns and Server Component details. --- # Implementation Workflow Follow these steps in order when adding view transitions to an app. Each step builds on the previous one. Use the official [React `<ViewTransition>` reference](https://react.dev/reference/react/ViewTransition) and [Next.js guide](https://nextjs.org/docs/app/guides/view-transitions) for API behavior. This file focuses on audit order, integration decisions, and verification. ## Step 1: Audit the App Before writing any code, scan the codebase thoroughly. Search for: - **Every `<Link>` and `router.push`** — these are your navigation triggers. Open every file that contains one. - **Every `<Suspense>` boundary** — each one is a candidate for a reveal animation. Check what its fallback renders. - **Every page/route component** — list them all. Each page needs a VT placement decision. - **Persistent elements** — headers, navbars, sidebars, sticky controls that stay on screen across navigations. These need `viewTransitionName` isolation. - **Shared visual elements** — images, cards, or avatars that appear on both a source and target view (e.g., a thumbnail in a list and the same image on a detail page). - **Skeleton-to-content control pairs** — if a Suspense f - skills/react-view-transitions/SKILL.md (14502 bytes)
--- name: vercel-react-view-transitions description: Guide for implementing smooth, native-feeling animations using React's View Transition API (`<ViewTransition>` component, `addTransitionType`, and CSS view transition pseudo-elements). Use this skill whenever the user wants to add page transitions, animate route changes, create shared element animations, animate enter/exit of components, animate list reorder, implement directional (forward/back) navigation animations, or integrate view transitions in Next.js. Also use when the user mentions view transitions, `startViewTransition`, `ViewTransition`, transition types, or asks about animating between UI states in React without third-party animation libraries. license: MIT metadata: author: vercel version: "1.0.0" --- # React View Transitions Animate between UI states using the browser's native `document.startViewTransition`. Declare *what* with `<ViewTransition>`, trigger *when* with `startTransition` / `useDeferredValue` / `Suspense`, control *how* with CSS classes. Unsupported browsers skip animations gracefully. ## When to Animate Every `<ViewTransition>` should communicate a spatial relationship or continuity. If you can't articulate what it communicates, don't add it. Implement **all** applicable patterns from this list, in this order: | Priority | Pattern | What it communicates | |----------|---------|---------------------| | 1 | **Shared element** (`name`) | "Same thing — going deeper" | | 2 | **Suspense reveal** | "Data loaded" | | 3 | **List identity** (per-item `key`) | "Same items, new arrangement" | | 4 | **State change** (`enter`/`exit`) | "Something appeared/disappeared" | | 5 | **Route change** (page-level) | "Going to a new place" | This is an implementation order, not a "pick one" list. Implement every pattern that fits the app. Only skip a pattern if the app has no use case for it. ### Choosing Animation Style | Context | Animation | Why | |---------|-----------|-----| | Hierarchical navigation (list → detail) | Type-keyed `nav-forward` / `nav-back` | Communicates spatial depth | | Lateral navigation (tab-to-tab) | Bare `<ViewTransition>` (fade) or `default="none"` | No depth to communicate | | Suspense reveal | `enter`/`exit` string props | Content arriving | | Revalidation / background refresh | `default="none"` | Silent — no animation needed | Reserve directional slides for hierarchical navigation (list → detail) and ordered sequences (prev/next photo, carousel, paginated results). For ordered sequences, the direction communicates position: "next" slides from right, "previous" from left. Lateral/unordered navigation (tab-to-tab) should not use directional slides — it falsely implies spatial depth. --- ## Availability - **Next.js:** Do **not** install `react@canary` — the App Router already bundles React canary internally. `ViewTransition` works out of the box. `npm ls react` may show a stable-looking version; this is expected. - **Without Next.js:** Use stable `react` and `react-dom` 19.3 or newer (`ViewTransition` and `addTransitionType` became stable in React 19.3). Earlier stable React versions do not include these APIs. - Browser support: Chromium 125+ (React needs the v2 object form of `startViewTransition`), Firefox 144+, Safari 18.2+. Graceful degradation on unsupported browsers. --- ## Implementation Workflow When adding view transitions to an existing app, **follow [references/implementation.md](references/implementation.md) step by step.** Start with the audit — do not skip it. Use [references/css-recipes.md](references/css-recipes.md) for the applicable CSS and adapt it to the app. --- ## Core Concepts ### The `<ViewTransition>` Component ```jsx import { ViewTransition } from 'react'; <ViewTransition> <Component /> </ViewTransition> ``` React auto-assigns a unique `view-transition-name` and calls `document.startViewTransition` behind the scenes. Never call `startViewTransition` yourself. ### Animation Triggers | Trigger | When it fires | |---------|--------------| | **enter** | `<ViewTransition>` first inserted during a Transition | | **exit** | `<ViewTransition>` first removed during a Transition | | **update** | DOM mutations inside a `<ViewTransition>`, or the boundary itself changing size/position due to an immediate sibling. With nested VTs, mutation applies to the innermost one | | **share** | Named VT unmounts and another with same `name` mounts in the same Transition | Only `startTransition`, `useDeferredValue`, or `Suspense` activate VTs. Regular `setState` does not animate. ### Critical Placement Rule `<ViewTransition>` only activates enter/exit if it appears **before any DOM nodes**: ```jsx // Works <ViewTransition enter="auto" exit="auto"> <div>Content</div> </ViewTransition> // Broken — div wraps the VT, suppressing enter/exit <div> <ViewTransition enter="auto" exit="auto"> <div>Content</div> </ViewTransition> </div> ``` --- ## Styling with View Transition Classes ### Props Values: `"auto"` (browser cross-fade), `"none"` (disabled), `"class-name"` (custom CSS), or `{ [type]: value }` for type-specific animations. ```jsx <ViewTransition default="none" enter="slide-in" exit="slide-out" share="morph" /> ``` If `default` is `"none"`, all triggers are off unless explicitly listed. ### CSS Pseudo-Elements - `::view-transition-old(.class)` — outgoing snapshot - `::view-transition-new(.class)` — incoming snapshot - `::view-transition-group(.class)` — container - `::view-transition-image-pair(.class)` — old + new pair See [references/css-recipes.md](references/css-recipes.md) for ready-to-use animation recipes. --- ## Transition Types Tag transitions with `addTransitionType` so VTs can pick different animations based on context. Call it multiple times to stack types — different VTs in the tree react to different types: ```jsx startTransition(() => { addTransitionType('nav-forward'); addTransitionType('select-item'); router.push('/detail/1'); }); ``` Pass an object to map types to CSS classes. Works on `enter`, `exit`, **and** `share`: ```jsx <ViewTransition enter={{ 'nav-forward': 'slide-from-right', 'nav-back': 'slide-from-left', default: 'none' }} exit={{ 'nav-forward': 'slide-to-left', 'nav-back': 'slide-to-right', default: 'none' }} share={{ 'nav-forward': 'morph-forward', 'nav-back': 'morph-back', default: 'morph' }} default="none" > <Page /> </ViewTransition> ``` `enter` and `exit` don't have to be symmetric. For example, fade in but slide out directionally: ```jsx <ViewTransition enter={{ 'nav-forward': 'fade-in', 'nav-back': 'fade-in', default: 'none' }} exit={{ 'nav-forward': 'nav-forward', 'nav-back': 'nav-back', default: 'none' }} default="none" > ``` **TypeScript:** `ViewTransitionClassPerType` requires a `default` key in the object. For apps with multiple pages, extract the type-keyed VT into a reusable wrapper: ```jsx export function DirectionalTransition({ children }: { children: React.ReactNode }) { return ( <ViewTransition enter={{ 'nav-forward': 'nav-forward', 'nav-back': 'nav-back', default: 'none' }} exit={{ 'nav-forward': 'nav-forward', 'nav-back': 'nav-back', default: 'none' }} default="none" > {children} </ViewTransition> ); } ``` ### `router.back()` and Browser Back Button `router.back()` and the browser's back/forward buttons carry **no transition types**, so type-keyed animations (directional slides) resolve to their `default` and don't play — untyped shared-element morphs still apply. For typed animations, use `router.push()` with an explicit URL. ### Types and Suspense Types are available during navigation but **not** during subsequent Suspense reveals (separate transitions, no type). Use type maps for page-level enter/exit; use simple string props for Suspense reveals. ### Shared Element Readiness A shared element transition can pair elements only when both the old and new views are rendered in the same Transition. If incoming content suspends, only its fallback exists for that update; the resolved content appears in a later Suspense transition and can be animated separately. --- ## Shared Element Transitions Same `name` on two VTs — one unmounting, one mounting — creates a shared element morph: ```jsx <ViewTransition name="hero-image"> <img src="/thumb.jpg" onClick={() => startTransition(() => onSelect())} /> </ViewTransition> // On the other view — same name <ViewTransition name="hero-image"> <img src="/full.jpg" /> </ViewTransition> ``` - Only one VT with a given `name` can be mounted at a time — use unique names (`photo-${id}`). Watch for reusable components: if a component with a named VT is rendered in both a modal/popover *and* a page, both mount simultaneously and break the morph. Either make the name conditional (via a prop) or move the named VT out of the shared component into the specific consumer. - `share` takes precedence over `enter`/`exit`. Think through each navigation path: when no matching pair forms (e.g., the target page doesn't have the same name), `enter`/`exit` fires instead. Consider whether the element needs a fallback animation for those paths. - Two ways a wired-up morph silently never fires: (1) `default="none"` with no explicit `share` prop — share resolves to none; (2) type-keyed `share` where the navigation never adds the type — a plain link click resolves the map's `default`. Every link that should morph must add the type (`transitionTypes` on `next/link`, or `addTransitionType`). - Never use a fade-out exit on pages with shared morphs — use a directional slide instead. --- ## Common Patterns ### Enter/Exit ```jsx {show && ( <ViewTransition enter="fade-in" exit="fade-out"><Panel /></ViewTransition> )} ``` ### List Reorder ```jsx {items.map(item => ( <ViewTransition key={item.id}><ItemCard item={item} /></ViewTransition> ))} ``` Trigger inside `startTransition`. Avoid wrapper `<div>`s between list and VT. ### Layout Displacement Morph Only content inside an activated boundary animates position — everything else teleports to its new layout spot. Wrap the sibling content below a growing/shrinking list in a bare `<ViewTransition>` so it glides instead of jumping. See [Layout Displacement Morph](references/patterns.md#layout-displacement-morph). ### Composing Shared Elements with List Identity Shared elements and list identity are independent concerns — don't confuse one for the other. When a list item contains a shared element (e.g., an image that morphs into a detail view), use two nested `<ViewTransition>` boundaries: ```jsx {items.map(item => ( <ViewTransition key={item.id}> {/* list identity */} <Link href={`/items/${item.id}`}> <ViewTransition name={`item-image-${item.id}`} share="morph"> {/* shared element */} <Image src={item.image} /> </ViewTransition> <p>{item.name}</p> </Link> </ViewTransition> ))} ``` The outer VT handles list reorder/enter animations. The inner VT handles the cross-route shared element morph. Missing either layer means that animation silently doesn't happen. ### Force Re-Enter with `key` ```jsx <ViewTransition key={searchParams.toString()} enter="slide-up" default="none"> <ResultsGrid /> </ViewTransition> ``` **Caution:** If wrapping `<Suspense>`, changing `key` remounts the boundary and refetches. ### Suspense Fallback to Content Simple cross-fade: ```jsx <ViewTransition> <Suspense fallback={<Skeleton />}><Content /></Suspense> </ViewTransition> ``` Directional reveal: ```jsx <Suspense fallback={<ViewTransition exit="slide-down"><Skeleton /></ViewTransition>}> <ViewTransition enter="slide-up" default="none"><Content /></ViewTransition> </Suspense> ``` For more patterns, see [references/patterns.md](references/patterns.md). --- ## How Multiple VTs Interact Every VT matching the trigger fires simultaneously in a single `document.startViewTransition`. VTs in **different** transitions (navigation vs later Suspense resolve) don't compete. ### Use `default="none"` Deliberately Without it, every VT fires the browser cross-fade on **every** transition — Suspense resolves, `useDeferredValue` updates, background revalidations. Use `default="none"` on named/shared elements and type-keyed page VTs. But it also turns off `update` (layout/reflow morphs) and `share` (a named pair with no explicit `share` prop never morphs). Keyed list items and displaced siblings *want* update — leave them bare or set `update="auto"`. ### Two Patterns Coexist **Pattern A — Directional slides:** Type-keyed VT on each page, fires during navigation. **Pattern B — Suspense reveals:** Simple string props, fires when data loads (no type). They coexist because they fire at different moments. `default="none"` on both prevents cross-interference. Always pair `enter` with `exit`. Place directional VTs in page components, not layouts. ### Nested VT Limitation When a parent VT mounts/unmounts **as one unit** with nested VTs inside it, the nested ones do not fire their own enter/exit — only the outermost VT animates. (A child VT mounted inside a *persistent* parent VT fires enter/exit normally.) Per-item staggered animations during page navigation are not currently available in Next.js; see [troubleshooting](references/troubleshooting.md) for the upstream experimental status. --- ## Next.js Integration For Next.js integration (`transitionTypes` on `next/link` and `useRouter`, App Router patterns, Server Components), see [references/nextjs.md](references/nextjs.md). --- ## Accessibility Always add the reduced motion CSS from [references/css-recipes.md](references/css-recipes.md#reduced-motion) to your global stylesheet. --- ## Reference Files - **[references/implementation.md](references/implementation.md)** — Step-by-step implementation workflow. - **[references/patterns.md](references/patterns.md)** — Patterns, animation timing, and events API. - **[references/troubleshooting.md](references/troubleshooting.md)** — Symptom-driven debugging and runtime limitations. - **[references/css-recipes.md](references/css-recipes.md)** — Ready-to-use CSS animation recipes. - **[references/nextjs.md](references/nextjs.md)** — Next.js App Router patterns and Server Component details. ## Full Compiled Document For the complete guide with all reference files expanded: `AGENTS.md` - skills/vercel-cli-with-tokens/SKILL.md (10476 bytes)
--- name: vercel-cli-with-tokens description: Deploy and manage projects on Vercel using token-based authentication. Use when working with Vercel CLI using access tokens rather than interactive login — e.g. "deploy to vercel", "set up vercel", "add environment variables to vercel". metadata: author: vercel version: "1.0.0" --- # Vercel CLI with Tokens Deploy and manage projects on Vercel using the CLI with token-based authentication, without relying on `vercel login`. ## Step 1: Locate the Vercel Token Before running any Vercel CLI commands, identify where the token is coming from. Work through these scenarios in order: ### A) `VERCEL_TOKEN` is already set in the environment ```bash printenv VERCEL_TOKEN ``` If this returns a value, you're ready. Skip to Step 2. ### B) Token is in a `.env` file under `VERCEL_TOKEN` ```bash grep '^VERCEL_TOKEN=' .env 2>/dev/null ``` If found, export it: ```bash export VERCEL_TOKEN=$(grep '^VERCEL_TOKEN=' .env | cut -d= -f2-) ``` ### C) Token is in a `.env` file under a different name Look for any variable that looks like a Vercel token (Vercel tokens typically start with `vca_`): ```bash grep -i 'vercel' .env 2>/dev/null ``` Inspect the output to identify which variable holds the token, then export it as `VERCEL_TOKEN`: ```bash export VERCEL_TOKEN=$(grep '^<VARIABLE_NAME>=' .env | cut -d= -f2-) ``` ### D) No token found — ask the user If none of the above yield a token, ask the user to provide one. They can create a Vercel access token at vercel.com/account/tokens. --- **Important:** Once `VERCEL_TOKEN` is exported as an environment variable, the Vercel CLI reads it natively — **do not pass it as a `--token` flag**. Putting secrets in command-line arguments exposes them in shell history and process listings. ```bash # Bad — token visible in shell history and process listings vercel deploy --token "vca_abc123" # Good — CLI reads VERCEL_TOKEN from the environment export VERCEL_TOKEN="vca_abc123" vercel deploy ``` ## Step 2: Locate the Project and Team Similarly, check for the project ID and team scope. These let the CLI target the right project without needing `vercel link`. ```bash # Check environment printenv VERCEL_PROJECT_ID printenv VERCEL_ORG_ID # Or check .env grep -i 'vercel' .env 2>/dev/null ``` **If you have a project URL** (e.g. `https://vercel.com/my-team/my-project`), extract the team slug: ```bash # e.g. "my-team" from "https://vercel.com/my-team/my-project" echo "$PROJECT_URL" | sed 's|https://vercel.com/||' | cut -d/ -f1 ``` **If you have both `VERCEL_ORG_ID` and `VERCEL_PROJECT_ID` in your environment**, export them — the CLI will use these automatically and skip any `.vercel/` directory: ```bash export VERCEL_ORG_ID="<org-id>" export VERCEL_PROJECT_ID="<project-id>" ``` Note: `VERCEL_ORG_ID` and `VERCEL_PROJECT_ID` must be set together — setting only one causes an error. ## CLI Setup Ensure the Vercel CLI is installed and up to date: ```bash npm install -g vercel vercel --version ``` ## Deploying a Project Always deploy as **preview** unless the user explicitly requests production. Choose a method based on what you have available. ### Quick Deploy (have project ID — no linking needed) When `VERCEL_TOKEN` and `VERCEL_PROJECT_ID` are set in the environment, deploy directly: ```bash vercel deploy -y --no-wait ``` With a team scope (either via `VERCEL_ORG_ID` or `--scope`): ```bash vercel deploy --scope <team-slug> -y --no-wait ``` Production (only when explicitly requested): ```bash vercel deploy --prod --scope <team-slug> -y --no-wait ``` Check status: ```bash vercel inspect <deployment-url> ``` ### Full Deploy Flow (no project ID — need to link) Use this when you have a token and team but no pre-existing project ID. #### Check project state first ```bash # Does the project have a git remote? git remote get-url origin 2>/dev/null # Is it already linked to a Vercel project? cat .vercel/project.json 2>/dev/null || cat .vercel/repo.json 2>/dev/null ``` #### Link the project **With git remote (preferred):** ```bash vercel link --repo --scope <team-slug> -y ``` Reads the git remote and connects to the matching Vercel project. Creates `.vercel/repo.json`. More reliable than plain `vercel link`, which matches by directory name. **Without git remote:** ```bash vercel link --scope <team-slug> -y ``` Creates `.vercel/project.json`. **Link to a specific project by name:** ```bash vercel link --project <project-name> --scope <team-slug> -y ``` If the project is already linked, check `orgId` in `.vercel/project.json` or `.vercel/repo.json` to verify it matches the intended team. #### Deploy after linking **A) Git Push Deploy — has git remote (preferred)** Git pushes trigger automatic Vercel deployments. 1. **Ask the user before pushing.** Never push without explicit approval. 2. Commit and push: ```bash git add . git commit -m "deploy: <description of changes>" git push ``` 3. Vercel builds automatically. Non-production branches get preview deployments. 4. Retrieve the deployment URL: ```bash sleep 5 vercel ls --format json --scope <team-slug> ``` Find the latest entry in the `deployments` array. **B) CLI Deploy — no git remote** ```bash vercel deploy --scope <team-slug> -y --no-wait ``` Check status: ```bash vercel inspect <deployment-url> ``` ### Deploying from a Remote Repository (code not cloned locally) 1. Clone the repository: ```bash git clone <repo-url> cd <repo-name> ``` 2. Link to Vercel: ```bash vercel link --repo --scope <team-slug> -y ``` 3. Deploy via git push (if you have push access) or CLI deploy. ### About `.vercel/` Directory A linked project has either: - `.vercel/project.json` — from `vercel link`. Contains `projectId` and `orgId`. - `.vercel/repo.json` — from `vercel link --repo`. Contains `orgId`, `remoteName`, and a `projects` map. Not needed when `VERCEL_ORG_ID` + `VERCEL_PROJECT_ID` are both set in the environment. **Do NOT** run `vercel project inspect` or `vercel link` in an unlinked directory to detect state — they will interactively prompt or silently link as a side-effect. `vercel ls` is safe (in an unlinked directory it defaults to showing all deployments for the scope). `vercel whoami` is safe anywhere. ## Managing Environment Variables ```bash # Set for all environments echo "value" | vercel env add VAR_NAME --scope <team-slug> # Set for a specific environment (production, preview, development) echo "value" | vercel env add VAR_NAME production --scope <team-slug> # List environment variables vercel env ls --scope <team-slug> # Pull env vars to local .env.local file vercel env pull --scope <team-slug> # Remove a variable vercel env rm VAR_NAME --scope <team-slug> -y ``` ## Inspecting Deployments ```bash # List recent deployments vercel ls --format json --scope <team-slug> # Inspect a specific deployment vercel inspect <deployment-url> # View build logs (requires Vercel CLI v35+) vercel inspect <deployment-url> --logs # View runtime request logs (follows live by default; add --no-follow for a one-shot snapshot) vercel logs <deployment-url> ``` ## Managing Domains ```bash # List domains vercel domains ls --scope <team-slug> # Add a domain to the project — linked or env-linked directory (1 arg) vercel domains add <domain> --scope <team-slug> # Add a domain — unlinked directory (requires <project> positional) vercel domains add <domain> <project> --scope <team-slug> ``` ## Stripe Projects Plan Changes If this project is managed by Stripe Projects. **Ask the user before running any paid or destructive plan change** — upgrades bill a real card, downgrades remove seats. First run `stripe projects status --json` to confirm the Vercel resource's local name. The examples below assume the default (`vercel-plan`); substitute the actual name if it was renamed at `stripe projects add` time. - **Upgrade to Pro:** `stripe projects add vercel/pro` (or `stripe projects upgrade vercel-plan pro`) - **Downgrade to Hobby:** `stripe projects downgrade vercel-plan hobby` ### What Pro gives you - $20/month platform fee, includes $20/month of usage credit. - Turbo build machines (30 vCPUs, 60 GB memory) by default for new projects — significantly faster builds than Hobby. - 1 deploying seat + unlimited free Viewer seats (read-only collaborators, preview comments). - Higher included allocations (1 TB Fast Data Transfer, 10M Edge Requests per month). - Paid add-ons available: SAML SSO, HIPAA BAA, Flags Explorer, Observability Plus, Speed Insights, Web Analytics Plus. Full details: https://vercel.com/docs/plans/pro-plan ## Working Agreement - **Never pass `VERCEL_TOKEN` as a `--token` flag.** Export it as an environment variable and let the CLI read it natively. - **Check the environment for tokens before asking the user.** Look in the current env and `.env` files first. - **Default to preview deployments.** Only deploy to production when explicitly asked. - **Ask before pushing to git.** Never push commits without the user's approval. - **Do not modify `.vercel/` files directly.** The CLI manages this directory. Reading them (e.g. to verify `orgId`) is fine. - **Do not curl/fetch deployed URLs to verify.** Just return the link to the user. - **Use `--format json`** when structured output will help with follow-up steps. - **Use `-y`** on commands that prompt for confirmation to avoid interactive blocking. ## Troubleshooting ### Token not found Check the environment and any `.env` files present: ```bash printenv | grep -i vercel grep -i vercel .env 2>/dev/null ``` ### Authentication error If the CLI fails with `Authentication required`: - The token may be expired or invalid. - Verify: `vercel whoami` (uses `VERCEL_TOKEN` from environment). - Ask the user for a fresh token. ### Wrong team Verify the scope is correct: ```bash vercel whoami --scope <team-slug> ``` ### Build failure Check the build logs: ```bash vercel inspect <deployment-url> --logs ``` Common causes: - Missing dependencies — ensure `package.json` is complete and committed. - Missing environment variables — add with `vercel env add`. - Framework misconfiguration — check `vercel.json`. Vercel auto-detects frameworks (Next.js, Remix, Vite, etc.) from `package.json`; override with `vercel.json` if detection is wrong. ### CLI not installed ```bash npm install -g vercel ```
- skills/vercel-optimize/AGENTS.md (1964 bytes)
# vercel-optimize Cross-agent entry point for the Vercel Optimize skill. The full procedure is in [SKILL.md](./SKILL.md). Use this skill when the user asks to optimize a Vercel project, reduce a Vercel bill, investigate slow or expensive routes, find caching opportunities, reduce function invocations, or produce a Vercel cost/performance report. Do not use it for projects that are not deployed on Vercel, greenfield projects with no traffic, or general code review. ## Requirements - Node.js 20+ - Vercel CLI with `vercel metrics`, `vercel usage`, `vercel contract`, and `vercel api` support; v53+ is this skill's compatibility floor - Authenticated Vercel CLI session - Linked Vercel project directory (`vercel link`) for route metrics. `VERCEL_PROJECT_ID` can help resolve project config, but it does not replace directory linkage for `vercel metrics`. The project must resolve to a CLI-safe team or personal scope so `vercel metrics`, `vercel usage`, and `vercel contract` all run against the same account. - Observability Plus for per-route metric analysis ## Procedure 1. Read [SKILL.md](./SKILL.md). 2. Collect Vercel signals before reading source files. 3. Gate candidates with deterministic scripts. 4. Investigate only files named by launched candidates. 5. Verify recommendations mechanically before rendering the report. The hard rules are in [references/doctrine.md](./references/doctrine.md): observability first, deterministic gates, candidate-bound scope, and version-aware citations. ## Install Preferred: ```bash npx skills add vercel-labs/agent-skills --skill vercel-optimize ``` Manual project install: ```bash mkdir -p .agents/skills cp -R <agent-skills-repo>/skills/vercel-optimize .agents/skills/ ``` Then add this to the project `AGENTS.md`: ```md When optimizing Vercel cost or performance, follow `.agents/skills/vercel-optimize/SKILL.md` before proposing changes. Collect Vercel metrics before reading source files. ```
- skills/vercel-optimize/SKILL.md (17311 bytes)
--- name: vercel-optimize description: "Use for Vercel cost and performance optimization on deployed projects, especially Next.js, SvelteKit, Nuxt, and limited Astro apps. Collect Vercel metrics, usage, project config, and code scan results first; investigate only metric-backed candidates; produce ranked recommendations grounded in verified files and version-aware Vercel/framework docs. Trigger for Vercel bill reduction, slow or expensive routes, caching opportunities, Function Invocations, Build Minutes, Fast Data Transfer, Core Web Vitals, Bot Management, Fluid compute, or cost breakdown requests." metadata: version: "1.2.0" --- # Vercel Optimize Run an observability-first Vercel optimization audit. Do not inspect source files until `signals.json` exists and a deterministic gate points to a route, file, or project setting. Core doctrine: read [references/doctrine.md](references/doctrine.md) if any rule is unclear. - Metrics first. Recommendations start from Vercel production signals, not repo-wide grep. - Deterministic gates. `scripts/gate-investigations.mjs` decides what deserves investigation. - Candidate-bound scope. Read only files named by a candidate or a route-local import chain. - Version-aware citations. Use only `references/docs-library.json`; invalid or version-mismatched citations are stripped. - Customer copy. Read [references/voice.md](references/voice.md) before writing report text or chat output. ## Prerequisites - Vercel CLI v53+ with `vercel metrics`, `vercel usage`, `vercel contract`, and `vercel api`. - Authenticated CLI session: `vercel login`. - Linked app directory: `vercel link`. `VERCEL_PROJECT_ID` can help resolve project config, but `vercel metrics` still requires directory linkage. The link or environment must include the intended project org/team/user scope so the collector can resolve a CLI-safe `--scope` and keep `vercel metrics`, `vercel usage`, and `vercel contract` on the same account. - Node.js 20+. - Observability Plus for route-level metric-backed recommendations. Never put auth tokens in shell commands. Do not type `VERCEL_TOKEN=...`, `--token ...`, or `Authorization: Bearer ...` into commands that may be echoed in chat. ## Framework Support The preflight reads `package.json` and sets expectations before metric fan-out. | Framework | Status | Notes | |---|---|---| | Next.js App Router | supported | strongest route mapping, scanners, playbooks, citations | | Next.js Pages Router | supported | scoped to Pages Router idioms when detected | | SvelteKit | supported | route mapping for `src/routes` files and SvelteKit scanner | | Nuxt | supported | route mapping plus generic/platform checks; fewer framework-specific recs | | Astro | limited | route mapping plus generic checks; fewer framework-specific recs | | Hono / Remix / unknown | blocked by default | continue only if the user accepts a limited platform/code-only audit | If unsupported, stop and ask before scanning or gating: ```text This project uses <framework>. Vercel Optimize supports metric-backed code recommendations for Next.js, SvelteKit, and Nuxt. Astro support is limited. For <framework>, I can still run a limited platform/scanner audit, but route-level Vercel metrics may not map back to source files. Do you want me to continue with the limited audit, or stop here? ``` If the user continues, rerun collection with `--continue-unsupported-framework`. ## Run Directory Use a fresh run directory for every audit. Do not reuse briefs, sub-agent outputs, or reports across runs. ```bash RUN_DIR="$(mktemp -d -t vercel-optimize-XXXXXX)" ``` ## Pipeline ### 1. Collect, scan, and merge signals Run from the linked app directory or pass `--cwd` where a script supports it. Keep stdout JSON separate from stderr logs. Do not combine streams. ```bash node scripts/collect-signals.mjs [projectId] > "$RUN_DIR/vercel-signals.json" 2> "$RUN_DIR/collect.stderr" node -e 'JSON.parse(require("fs").readFileSync(process.argv[1], "utf8"))' "$RUN_DIR/vercel-signals.json" node scripts/scan-codebase.mjs <repo-root> > "$RUN_DIR/codebase.json" node scripts/merge-signals.mjs "$RUN_DIR/vercel-signals.json" "$RUN_DIR/codebase.json" --out "$RUN_DIR/signals.json" ``` Collection details, schemas, metric IDs, and degradation behavior live in [references/data-collection.md](references/data-collection.md). The metric registry is [lib/queries.mjs](lib/queries.mjs); keep all queries on the shared 14-day window. `collect-signals.mjs` resolves the linked project owner to `commandScope.cliScope` and verifies that the resolved account can read the resolved project before it checks Observability Plus. Downstream scripts reuse that scope for every Vercel CLI command that accepts `--scope`. Do not run `vercel usage`, `vercel metrics`, or `vercel contract` manually without the same scope; unscoped usage can report the user's personal organization while route metrics come from the team project. If project or scope resolution is ambiguous, stop and ask the user which Vercel project and team/personal scope they want audited. Do not infer the intended scope from the current `vercel whoami` team, and do not proceed with metrics, usage, or contract collection until the link, an exact project match in `.vercel/repo.json`, or `VERCEL_PROJECT_ID` + `VERCEL_ORG_ID` identifies the intended account. Use this prompt for `PROJECT_SCOPE_UNRESOLVED`, `SCOPE_UNRESOLVED`, or `PROJECT_SCOPE_MISMATCH`: ```text I can't safely identify the Vercel project and account for this audit yet. Please confirm the Vercel project name or ID and the team slug/name, or tell me it's under your personal account. Once confirmed, I'll relink or rerun collection against that exact scope before checking metrics. ``` ### 1.1 Stop on blockers Check blockers before gating: ```bash jq '{frameworkSupportBlocker, observabilityPlus, observabilityPlusUsable, observabilityPlusBlocker, observabilityPlusBlockerDetail}' "$RUN_DIR/signals.json" ``` Required actions: - `frameworkSupportBlocker === "unsupported_framework"`: use the unsupported-framework prompt above. - `PROJECT_SCOPE_UNRESOLVED`, `SCOPE_UNRESOLVED`, or `PROJECT_SCOPE_MISMATCH`: stop and ask which Vercel project and team/personal scope the user wants audited. For team projects, rerun after `vercel link --yes --project <project-name-or-id> --team <team-slug>`; for personal projects, rerun after linking under the intended user account or after setting both `VERCEL_PROJECT_ID` and `VERCEL_ORG_ID`. - `observabilityPlusBlocker === null`: continue. - `no_traffic`: tell the user route metrics are sparse; continue only if they accept limited output. - `payment_required` or `no_oplus_probe`: render [references/observability-plus.md](references/observability-plus.md) verbatim and ask. - `project_disabled`: tell the user to enable Observability Plus for the project or accept a limited audit. - `daily_quota_exceeded`: stop and tell the user the Observability query quota is exhausted; retry after the next UTC midnight reset, or ask whether to continue with a limited code-only audit. - `not_linked`: link the app directory, then rerun Step 1. If app path and project are known: ```bash vercel link --yes --project <project-name-or-id> --cwd <app-dir> # add --team <team-id-or-slug> when known ``` - `forbidden` or `project_not_found`: fix auth/team scope. Do not pitch Observability Plus. - `all_failed_other`: show the raw error code and ask whether to continue in limited code-only mode. Do not silently fall back to code-only mode. If the user accepts a limited audit, rerun collection with: ```bash node scripts/collect-signals.mjs [projectId] --continue-without-observability > "$RUN_DIR/vercel-signals.json" 2> "$RUN_DIR/collect.stderr" ``` Then scan and merge again. ### 2. Gate candidates ```bash node scripts/gate-investigations.mjs "$RUN_DIR/signals.json" > "$RUN_DIR/gate.json" ``` Output shape: - `toLaunch`: code-scope candidates to investigate. - `platform`: project/account-scope recommendations. - `gated`: skipped, covered, or disqualified candidates that must still appear in the report. - `budget`: candidate budget and selection mode. Default budget is 6 code-scope candidates with a diversity guardrail. To expand: ```bash node scripts/gate-investigations.mjs "$RUN_DIR/signals.json" --max-candidates 12 > "$RUN_DIR/gate.json" node scripts/gate-investigations.mjs "$RUN_DIR/signals.json" --max-candidates all > "$RUN_DIR/gate.json" ``` Generated candidate docs: [references/candidates.md](references/candidates.md). ### 2.1 Ask about audit scope when needed Before deep-dive, run: ```bash node scripts/budget-summary.mjs "$RUN_DIR/gate.json" --format json > "$RUN_DIR/budget-summary.json" ``` If `shouldAsk` is false, continue. If `shouldAsk` is true: 1. Print `exactChatMessage.body` exactly as returned. Do not summarize, truncate, reorder, or rewrite it. 2. Then ask `questionText` using `questionPayload` when the host supports structured questions. 3. If the user chooses a different number, rerun the gate with `--max-candidates <choice>`. Never put the long preview inside the question field. The preview and the question are separate surfaces. ### 2.2 Deep-dive and reconcile ```bash node scripts/deep-dive.mjs "$RUN_DIR/signals.json" "$RUN_DIR/gate.json" --cwd <project-dir> > "$RUN_DIR/investigation-evidence.json" node scripts/reconcile-candidates.mjs "$RUN_DIR/investigation-evidence.json" \ --gate "$RUN_DIR/gate.json" \ --out "$RUN_DIR/reconciled-investigation.json" ``` `--cwd` must be the linked project directory so `deep-dive.mjs` can verify the same project link and reuse `signals.json.commandScope.cliScope` for any follow-up `vercel metrics` calls. Reconciliation deterministically converts disproven candidates into observations before any source investigation: - `metric_mismatch` - `error_storm` - `deployment_regression` - `scanner_only_no_metric` ### 2.3 Generate briefs and investigate List the work: ```bash node scripts/prepare-investigation-brief.mjs "$RUN_DIR/signals.json" "$RUN_DIR/reconciled-investigation.json" --list > "$RUN_DIR/briefs-manifest.json" ``` Generate one brief for every entry in `briefs-manifest.json.briefs`. The `group` can be `toLaunch` or `platform`; do not generate only `toLaunch` briefs. ```bash mkdir -p "$RUN_DIR/briefs" "$RUN_DIR/sub-agent-outputs" node scripts/prepare-investigation-brief.mjs "$RUN_DIR/signals.json" "$RUN_DIR/reconciled-investigation.json" \ --group <brief.group> --index <brief.index> --out "$RUN_DIR/briefs/<brief.group>-<brief.index>.md" ``` Use `briefs-manifest.json.briefs[].label` for visible worker names, for example `Low cache-hit route on /docs/llm-digest/[...slug]`, not `toLaunch-7`. Fan-out rule: - 1-2 briefs: investigate inline. - 3+ briefs: spawn one sub-agent per brief when the host supports it. - Hosts without sub-agents: run inline serially. Sub-agent contract: - The brief is the whole prompt. - Read only files listed in the brief, plus route-local imports when needed. - Emit one JSON recommendation or one JSON no-change finding using [references/recommendations.md](references/recommendations.md). - Do not cite URLs outside the provided citation subset. - Do not recommend framework features unavailable in the detected version. If a sub-agent reaches for repo-wide grep, the candidate is malformed; drop or abstain rather than widening scope. ### 2.4 Collect outputs Save each raw investigation result in `$RUN_DIR/sub-agent-outputs/`, then collect: ```bash node scripts/collect-sub-agent-outputs.mjs \ --manifest "$RUN_DIR/briefs-manifest.json" \ --out "$RUN_DIR/recommendations.json" \ "$RUN_DIR/sub-agent-outputs/" ``` The collector extracts JSON, prepends pre-resolved records, enforces manifest order, and fails on missing, duplicate, unknown, or mismatched `candidateRef` values. ### 3. Verify recommendations ```bash node scripts/verify-and-regen.mjs "$RUN_DIR/recommendations.json" \ --signals "$RUN_DIR/signals.json" \ --repo-root <project-dir> \ --out "$RUN_DIR/verify.json" ``` This script extracts claims, verifies files/citations/version fit, grades quality, applies sanitizers, emits `verifiedRecommendations`, `withheldRecommendations`, `renderableRecommendations`, and creates `regenPlan` for failed or unsafe recommendations. Recommendation schema, writing rules, sanitizer order, and grading rules: [references/recommendations.md](references/recommendations.md). Verification rules: [references/verification.md](references/verification.md). For each `regenPlan` entry, rerun the same brief with a `Previous attempt failed these checks` section listing `topFailures`. Keep the regenerated output only if verification improves without gutting citations. ### 4. Render report and final message ```bash node scripts/render-report.mjs "$RUN_DIR/verify.json" "$RUN_DIR/gate.json" "$RUN_DIR/signals.json" \ --project <name> \ --out "$RUN_DIR/report.md" \ --message-out "$RUN_DIR/final-message.json" ``` Use `--debug-out "$RUN_DIR/debug.json"` only when developing the skill. Customer Markdown and chat output must not expose `passRate`, `quality`, sanitizer trails, raw sub-agent names, or other implementation fields. After rendering, print `final-message.json.body` verbatim and stop. Do not add highlights, debug notes, raw counts, sub-agent summaries, or extra explanation. Render-time dedupe, platform caps, and hard-safety drops can change the customer-visible count, so never summarize from raw `verify.json`. Report structure and impact framing: [references/scoring.md](references/scoring.md). ## Recommendation Rules Every recommendation must: - Trace to a launched candidate, platform candidate, pre-resolved observation, or verified traffic-independent scanner finding. - Include observed metric evidence from `signals.json` or `evidence.deepDive`. - Cite verified files with line numbers when code is involved. - Include at least one allowed citation that applies to the detected framework/version. - Use precise observed performance numbers. - Use cost magnitude phrases only; never customer-facing `$N` savings. - Do not recommend duration reductions for Vercel Workflow runtime endpoints (`/.well-known/workflow/v1/*`). These are generated orchestration routes for durable step/flow execution and should be hard-gated before investigation. - Workflow recommendations must name the boundary being changed. Valid examples: enqueue durable work and return a run ID instead of awaiting completion, fix stream replay/closure/locks, or reduce verified excess Workflow Steps/Storage. Do not infer cost savings from Workflow endpoint wall-clock duration. - For streaming, SSE, resumable chat, or other intentionally long-lived routes, do not frame wall-clock function duration as a problem by itself. Require evidence of avoidable pre-first-byte work, high active CPU, duplicate invocations, or post-response work that can move out of the user-visible path. - Name a - skills/web-design-guidelines/SKILL.md (2077 bytes)
--- name: web-design-guidelines description: Review UI code for Web Interface Guidelines compliance. Use when asked to "review my UI", "check accessibility", "audit design", "review UX", or "check my site against best practices". metadata: author: vercel version: "1.1.0" argument-hint: <file-or-pattern> --- # Web Interface Guidelines Review files for compliance with Web Interface Guidelines. ## How It Works 1. Read the bundled guidelines at [references/command.md](references/command.md) 2. Read the specified files (or prompt user for files/pattern) 3. Check against all rules in the guidelines 4. Output findings in the terse `file:line` format ## Guidelines Source The rules are bundled with this skill in the [references/command.md](references/command.md) file. Read that file before each review. Do not fetch rules from the network. The snapshot is pinned to a specific upstream commit: Source: https://github.com/vercel-labs/web-interface-guidelines/blob/434b7f91364665f2f733b310ec54809bf8f37937/command.md SHA-256: `d246b026f4f29b5823a9cc857f9edf3d2507002e055e32040cadeaf3b38e0234` The file contains all the rules and output format instructions. Where it says `$ARGUMENTS`, use the files or pattern the user asked to review. ## Updating the Guidelines To update the snapshot to a newer upstream version: 1. Get the latest commit SHA: `gh api repos/vercel-labs/web-interface-guidelines/commits/main --jq .sha` 2. Download it: `curl -fsSL https://raw.githubusercontent.com/vercel-labs/web-interface-guidelines/<SHA>/command.md -o references/command.md` 3. Review the changes, then update the Source URL and SHA-256 above (`shasum -a 256 references/command.md`) 4. Regenerate `skills/web-design-guidelines.zip` so it matches the updated folder ## Usage When a user provides a file or pattern argument: 1. Read [references/command.md](references/command.md) 2. Read the specified files 3. Apply all rules from the guidelines 4. Output findings using the format specified in the guidelines If no files specified, ask the user which files to review.
- skills/writing-guidelines/SKILL.md (1233 bytes)
--- name: writing-guidelines description: Review docs/prose for Writing Guidelines compliance. Use when asked to "review my docs", "check writing style", "audit prose", "review docs voice and tone", or "check this page against the writing handbook". metadata: author: vercel version: "1.0.0" argument-hint: <file-or-pattern> --- # Writing Guidelines Review files for compliance with Writing Guidelines. ## How It Works 1. Fetch the latest guidelines from the source URL below 2. Read the specified files (or prompt user for files/pattern) 3. Check against all rules in the fetched guidelines 4. Output findings in the terse `file:line` format ## Guidelines Source Fetch fresh guidelines before each review: ``` https://raw.githubusercontent.com/vercel-labs/writing-guidelines/main/command.md ``` Use WebFetch to retrieve the latest rules. The fetched content contains all the rules and output format instructions. ## Usage When a user provides a file or pattern argument: 1. Fetch guidelines from the source URL above 2. Read the specified files 3. Apply all rules from the fetched guidelines 4. Output findings using the format specified in the guidelines If no files specified, ask the user which files to review.