Compare commits
20 Commits
master
..
e0929b4511
| Author | SHA1 | Date | |
|---|---|---|---|
| e0929b4511 | |||
| 694b8bc77c | |||
| 2a344ad588 | |||
| 452693126c | |||
| 32f4059ae6 | |||
| d12e98bec1 | |||
| 063b460477 | |||
| 17dcb2162c | |||
| 7dc41260f1 | |||
| 7b1167717c | |||
| 27e03cc56c | |||
| 6430ab3eff | |||
| 70c3ebfd19 | |||
| cabab19649 | |||
| e3f9cefc24 | |||
| 852727d73d | |||
| 57e5e2451f | |||
| 844cc8137f | |||
| 63894f73db | |||
| e6bfe7c946 |
@@ -0,0 +1,319 @@
|
||||
---
|
||||
name: attack-surface
|
||||
description: >
|
||||
Strategic research framework that compresses months of market/competitive research into hours through structured power questions. Extracts unspoken industry insights, fragile market assumptions, and strategic attack surfaces from competitor data, reviews, and industry sources using parallel intelligence gathering.
|
||||
Use when user says "attack surface", "research the market", "competitive analysis", "analyze competitors", "find market opportunity", "stress-test this idea", "market research", "evaluate opportunity", "find blind spots", "market entry", or when they want to deeply understand a market, evaluate a new direction, find industry blind spots, assess a partnership, or analyze opportunities.
|
||||
Do NOT use for code review, testing, deployment, bug fixing, or implementation tasks.
|
||||
---
|
||||
|
||||
# Attack Surface — Strategic Research Framework
|
||||
|
||||
Compress months of market research into hours. The difference between 3 hours and 3 months isn't the amount of information — it's knowing which questions actually matter.
|
||||
|
||||
Instead of "summarize these" or "analyze the competition", this framework extracts:
|
||||
- **UNSPOKEN INSIGHTS** — what successful players understand that customers never say out loud
|
||||
- **FRAGILE ASSUMPTIONS** — beliefs the entire market is built on, and how they break
|
||||
- **ATTACK SURFACES** — the blind spots, the fragile consensus, the opening nobody is talking about
|
||||
|
||||
## Search Tool Selection
|
||||
|
||||
**Primary: Exa MCP** — Use `mcp__exa__web_search_exa`, `mcp__exa__crawling_exa`, and `mcp__exa__deep_researcher_start` when available. Exa is the best fit for neural search, crawling full pages, and deep research.
|
||||
|
||||
**Fallback: Built-in web browsing tools** — If Exa MCP is unavailable, use the Codex environment's web search and page-open tools to find sources, open pages, and extract evidence. Record the exact URLs you relied on.
|
||||
|
||||
**Detection:** At the start of Phase 2, check whether Exa MCP is available in the current environment. If it is not, use the built-in web tools for the entire session and note that in the Source Dossier.
|
||||
|
||||
## When to Use
|
||||
|
||||
- Entering a new market or vertical
|
||||
- Evaluating a new feature direction for an existing project
|
||||
- Assessing a partnership or platform opportunity
|
||||
- Stress-testing a business idea before committing
|
||||
- Finding competitive blind spots and underserved niches
|
||||
- Any strategic question that benefits from deep evidence-based analysis
|
||||
|
||||
## Workflow Overview
|
||||
|
||||
7 phases, alternating between automated intelligence gathering and user-guided analysis:
|
||||
|
||||
| Phase | Name | Mode | Output |
|
||||
|-------|------|------|--------|
|
||||
| 1 | Briefing | Interactive | Research brief |
|
||||
| 2 | Source Collection | Automated (parallel) | Source dossier |
|
||||
| 3 | Unspoken Insights | Automated + checkpoint | Insight report |
|
||||
| 4 | Fragile Assumptions | Automated + checkpoint | Assumption map |
|
||||
| 5 | Investor Stress-Test | Automated + checkpoint | Stress-test results |
|
||||
| 6 | Opportunity Mapping | Automated + checkpoint | Opportunity matrix |
|
||||
| 7 | Action Plan & Save | Automated | Final research document |
|
||||
|
||||
---
|
||||
|
||||
## Phase 1: Briefing
|
||||
|
||||
Start by understanding what the user wants to research. This is an interactive conversation — ask questions until you have a clear research brief.
|
||||
|
||||
**Gather:**
|
||||
1. **Target** — What market, industry, or opportunity? (e.g., "yacht brokerage SaaS", "AI flashcards for language teachers", "mobile reading apps")
|
||||
2. **Angle** — What's the user's position? Entering as newcomer, expanding existing product, evaluating partnership?
|
||||
3. **Known competitors** — Any specific companies or products the user already knows about?
|
||||
4. **User-provided sources** — URLs, files, documents the user wants included? Accept any format.
|
||||
5. **Specific questions** — Anything particular the user wants answered beyond the standard framework?
|
||||
|
||||
**Project context:** If the research relates to an existing project the user is working on, ask about the current product, tech stack, and strategic position. This grounds the analysis in real context rather than hypotheticals.
|
||||
|
||||
**Output a research brief** before proceeding:
|
||||
```
|
||||
Research Brief:
|
||||
- Target: [market/opportunity]
|
||||
- Angle: [newcomer / existing player / evaluator]
|
||||
- Known competitors: [list]
|
||||
- User sources: [list of URLs/files]
|
||||
- Key questions: [specific questions beyond standard framework]
|
||||
- Project context: [if applicable, key facts about the user's product]
|
||||
```
|
||||
|
||||
Ask user to confirm before proceeding to Phase 2.
|
||||
|
||||
---
|
||||
|
||||
## Phase 2: Source Collection
|
||||
|
||||
This is the intelligence-gathering phase. The quality of analysis depends on the quality and diversity of sources.
|
||||
|
||||
Use parallel gatherers only when the current Codex environment supports subagents and the user explicitly asked for delegation or parallel agent work. Otherwise, run the same research tracks yourself in the main thread using batched searches.
|
||||
|
||||
### Tool availability check
|
||||
|
||||
Before starting collection, check Exa MCP availability:
|
||||
- If Exa is available -> use Exa tools for search and crawling
|
||||
- If Exa is unavailable -> use the built-in web search and page-open tools instead
|
||||
|
||||
### What to gather
|
||||
|
||||
Cover 4-5 research tracks, each focused on a different source type. If subagents are available and explicitly requested, run up to 4 gatherers in parallel. Otherwise, execute the tracks yourself in sequence.
|
||||
|
||||
**Subagent 1: Competitor Intelligence**
|
||||
Search for and crawl 5-8 competitor landing pages, product pages, and pricing pages. Extract: value propositions, positioning, pricing models, feature lists, target audience language.
|
||||
|
||||
**Subagent 2: Customer Voice**
|
||||
Search Reddit, forums, review sites (G2, Trustpilot, Product Hunt, App Store reviews) for customer complaints, praise, and unmet needs in this market. Extract: recurring pain points, feature requests, emotional language, switching triggers.
|
||||
|
||||
**Subagent 3: Industry Analysis**
|
||||
Search for industry reports, expert analysis, trend pieces, and earnings call transcripts. Extract: market size, growth trends, key players, regulatory landscape, technology shifts.
|
||||
|
||||
**Subagent 4: Adjacent & Emerging**
|
||||
Search for startups entering this space, adjacent markets that could expand into it, and emerging technologies that could disrupt it. Extract: new entrants, pivot signals, technology trends, funding patterns.
|
||||
|
||||
**Subagent 5: User-Provided Sources** (if any)
|
||||
Crawl all URLs the user provided. Extract full content.
|
||||
|
||||
### Subagent prompt template
|
||||
|
||||
Read `references/gatherer-prompt.md` for the detailed prompt template to use for each gatherer or direct pass. Each pass receives:
|
||||
- The research brief from Phase 1
|
||||
- Its specific focus area
|
||||
- Instructions for which search tool family to use (Exa or built-in web tools)
|
||||
|
||||
### After collection
|
||||
|
||||
Compile all subagent results into a **Source Dossier** — a structured document with all collected evidence organized by source type. Present a summary to the user:
|
||||
|
||||
```
|
||||
Source Dossier Summary:
|
||||
- Search tools used: [Exa MCP / built-in web tools]
|
||||
- X competitor pages analyzed
|
||||
- X customer reviews/complaints collected
|
||||
- X industry reports found
|
||||
- X emerging players identified
|
||||
- X user-provided sources crawled
|
||||
Key themes so far: [2-3 sentences]
|
||||
```
|
||||
|
||||
Ask: "Sources collected. Anything you want me to search for specifically before we start analysis? Or should I proceed?"
|
||||
|
||||
---
|
||||
|
||||
## Phase 3: Unspoken Insights
|
||||
|
||||
The first analytical question — the one that separates this from generic "market analysis":
|
||||
|
||||
> "Based on all collected evidence: What does every successful player in this market understand that their customers never say out loud?"
|
||||
|
||||
This question works because it forces the analysis past surface-level features and pricing into the deeper truths that drive the market.
|
||||
|
||||
Run this as a dedicated analysis pass using the prompt from `references/analyst-prompt.md` (Section: Unspoken Insights). If subagents are available and the user explicitly requested delegation, use a subagent. Otherwise, perform the pass directly in the main thread.
|
||||
|
||||
**Present findings** to the user as 3-5 numbered insights, each with:
|
||||
- The insight itself (one clear sentence)
|
||||
- Evidence from sources (specific quotes, data points)
|
||||
- Why this matters strategically
|
||||
|
||||
**Checkpoint:** "Here are the unspoken insights I found. Do any of these surprise you? Want me to dig deeper on any of them, or should we move to fragile assumptions?"
|
||||
|
||||
---
|
||||
|
||||
## Phase 4: Fragile Assumptions
|
||||
|
||||
The second power question:
|
||||
|
||||
> "What are the 3-5 assumptions this entire market is built on, and what would have to be true for each one to be wrong?"
|
||||
|
||||
This question maps the market's attack surface — the beliefs everyone takes for granted that could be upended.
|
||||
|
||||
Run this as a dedicated analysis pass with the Source Dossier plus Phase 3 insights. Use the prompt from `references/analyst-prompt.md` (Section: Fragile Assumptions).
|
||||
|
||||
**Present findings** as a structured assumption map:
|
||||
|
||||
For each assumption:
|
||||
- **The assumption** (what everyone believes)
|
||||
- **Evidence it's true** (why people believe this)
|
||||
- **What breaks it** (specific conditions that would make it wrong)
|
||||
- **Fragility score** (1-5: how likely is it to break in the next 2-3 years?)
|
||||
- **If it breaks** (what happens to the market)
|
||||
|
||||
**Checkpoint:** "These are the fragile assumptions I found. Any you disagree with? Want to explore any further?"
|
||||
|
||||
---
|
||||
|
||||
## Phase 5: Investor Stress-Test
|
||||
|
||||
The third power question:
|
||||
|
||||
> "Write 5 questions a world-class investor would ask to destroy this business idea, then answer each one using only the evidence in our source dossier."
|
||||
|
||||
This is adversarial by design. The goal is to find every weak point before committing resources.
|
||||
|
||||
Run this as a dedicated analysis pass with the Source Dossier plus all prior analysis. Use the prompt from `references/analyst-prompt.md` (Section: Investor Stress-Test).
|
||||
|
||||
**Present findings** as 5 numbered challenges:
|
||||
|
||||
For each:
|
||||
- **The killer question** (phrased as an investor would ask it)
|
||||
- **The evidence-based answer** (citing only our sources)
|
||||
- **Confidence level** (strong / moderate / weak)
|
||||
- **Remaining risk** (what the answer doesn't fully address)
|
||||
|
||||
### Iterative Deepening
|
||||
|
||||
For any answer rated "weak" confidence, automatically follow up:
|
||||
|
||||
> "What's the strongest version of this argument and where does it still break?"
|
||||
|
||||
Continue until all weak points are either resolved or clearly flagged as genuine risks.
|
||||
|
||||
**Checkpoint:** "Here's the stress-test. X questions have strong answers, Y have remaining risks. Want to dig deeper on any of these?"
|
||||
|
||||
---
|
||||
|
||||
## Phase 6: Opportunity Mapping
|
||||
|
||||
Now synthesize everything into actionable opportunities:
|
||||
|
||||
> "Given all the unspoken insights, fragile assumptions, and blind spots we've found — what are the 3 highest-leverage entry points or strategic moves? For each, what's the evidence, what's the risk, and what would you need to validate first?"
|
||||
|
||||
Run this as a dedicated analysis pass with all prior analysis. Use the prompt from `references/analyst-prompt.md` (Section: Opportunity Mapping).
|
||||
|
||||
**Present** as an opportunity matrix:
|
||||
|
||||
| Opportunity | Evidence | Risk | Validation Needed | Leverage (1-5) |
|
||||
|-------------|----------|------|-------------------|----------------|
|
||||
| ... | ... | ... | ... | ... |
|
||||
|
||||
**Checkpoint:** "These are the highest-leverage opportunities I see. Which ones resonate? Should I develop any of them into a concrete action plan?"
|
||||
|
||||
---
|
||||
|
||||
## Phase 7: Action Plan & Save
|
||||
|
||||
Based on user's selections from Phase 6, create a concrete action plan:
|
||||
|
||||
1. **Immediate next steps** (this week)
|
||||
2. **Validation experiments** (this month)
|
||||
3. **Strategic moves** (this quarter)
|
||||
|
||||
### Save the Document
|
||||
|
||||
Compile ALL phases into a single research document and save it.
|
||||
|
||||
Use this format:
|
||||
|
||||
```markdown
|
||||
---
|
||||
id: RESEARCH-YYYY-MM-DD-attack-surface-{slug}
|
||||
created: YYYY-MM-DD
|
||||
topic: Attack Surface Analysis — {Topic}
|
||||
sources: [list of source types used]
|
||||
search_tools: [Exa MCP / built-in web tools]
|
||||
tags: [attack-surface, market-research, {topic-tags}]
|
||||
---
|
||||
|
||||
# Attack Surface: {Topic}
|
||||
|
||||
## Executive Summary
|
||||
[3-5 bullet points with the most important findings]
|
||||
|
||||
## Research Brief
|
||||
[From Phase 1]
|
||||
|
||||
## Source Dossier Summary
|
||||
[From Phase 2 — source counts and key themes]
|
||||
|
||||
## Unspoken Insights
|
||||
[From Phase 3]
|
||||
|
||||
## Fragile Assumptions
|
||||
[From Phase 4 — the assumption map]
|
||||
|
||||
## Investor Stress-Test
|
||||
[From Phase 5 — questions, answers, confidence levels]
|
||||
|
||||
## Opportunity Matrix
|
||||
[From Phase 6]
|
||||
|
||||
## Action Plan
|
||||
[From Phase 7]
|
||||
|
||||
## Raw Sources
|
||||
[Links to all sources consulted]
|
||||
```
|
||||
|
||||
Save to the project root as `RESEARCH-YYYY-MM-DD-attack-surface-{slug}.md`. Tell the user the file path and offer to discuss any findings further.
|
||||
|
||||
---
|
||||
|
||||
## Delegation Guidance
|
||||
|
||||
This skill works without subagents. Use the main thread by default, and only delegate when the user explicitly asks for subagents or parallel agent work and the environment supports it.
|
||||
|
||||
Read the reference files for detailed prompt templates:
|
||||
|
||||
- `references/gatherer-prompt.md` — Prompt template for Phase 2 source collection gatherers
|
||||
- `references/analyst-prompt.md` — Prompt templates for Phases 3-6 analysis passes
|
||||
|
||||
When delegating:
|
||||
- Phase 2: Launch up to 4 gatherers in parallel, one per search focus
|
||||
- Phases 3-6: Run sequentially because each pass depends on prior findings
|
||||
- Use a normal Codex subagent type that fits the environment; do not depend on Claude-specific agent naming
|
||||
- Give gatherers the research brief, search tool instructions, and their focus area
|
||||
- Give analysis passes a condensed Source Dossier plus the raw-source appendix or links when possible; do not bloat context with unnecessary full-page dumps
|
||||
|
||||
### Token Budget
|
||||
|
||||
This skill may require 6-10 major research and analysis passes. Estimated cost:
|
||||
- Phase 2: 4-6 gatherer passes x ~5-15K tokens each
|
||||
- Phases 3-6: 4 analysis passes x ~10-20K tokens each
|
||||
- Total: ~60-150K tokens per full research session
|
||||
|
||||
---
|
||||
|
||||
## Common Mistakes
|
||||
|
||||
| Mistake | Fix |
|
||||
|---------|-----|
|
||||
| Skipping Phase 1 briefing | The research brief focuses everything — never skip |
|
||||
| Generic searches | Use specific, targeted queries from the research brief |
|
||||
| Presenting analysis without evidence | Every insight must cite specific sources |
|
||||
| Moving past weak stress-test answers | Always run iterative deepening on weak answers |
|
||||
| Forgetting to save | Always save the final document at the end |
|
||||
| Ignoring user-provided sources | Crawl them FIRST — the user chose them for a reason |
|
||||
| Not checking available search tools first | Decide on Exa vs. built-in web tools before collecting sources |
|
||||
@@ -0,0 +1,7 @@
|
||||
interface:
|
||||
display_name: "Attack Surface Research"
|
||||
short_description: "Find fragile market assumptions and strategic openings"
|
||||
default_prompt: "Use $attack-surface to research this market, extract fragile assumptions, and map the best entry points."
|
||||
|
||||
policy:
|
||||
allow_implicit_invocation: true
|
||||
@@ -0,0 +1,151 @@
|
||||
# Analysis Prompt Templates
|
||||
|
||||
Use these templates when running Phases 3-6 analysis passes. Each pass receives the Source Dossier and prior analysis results, whether it is executed directly or via a subagent.
|
||||
|
||||
---
|
||||
|
||||
## Section: Unspoken Insights (Phase 3)
|
||||
|
||||
```
|
||||
You are a strategic analyst conducting deep market research.
|
||||
|
||||
Research brief:
|
||||
{RESEARCH_BRIEF}
|
||||
|
||||
Source Dossier:
|
||||
{FULL_SOURCE_DOSSIER}
|
||||
|
||||
Your task: Answer this question with rigorous evidence from the sources above:
|
||||
|
||||
"What does every successful player in this market understand that their customers never say out loud?"
|
||||
|
||||
This isn't about features or pricing. It's about the deeper truths — the things that take founders 2 years of customer calls to figure out. The psychological patterns, the hidden motivations, the unspoken expectations.
|
||||
|
||||
Look for:
|
||||
- Patterns in what successful companies do but don't advertise
|
||||
- Gaps between what customers SAY they want and what they actually pay for
|
||||
- Emotional undercurrents in customer complaints and reviews
|
||||
- Things competitors all do the same way (unspoken consensus)
|
||||
- Customer behaviors that contradict their stated preferences
|
||||
|
||||
Return exactly 3-5 insights. For each:
|
||||
1. **The insight** — one clear, provocative sentence
|
||||
2. **Evidence** — 2-3 specific quotes or data points from the sources, with source URLs
|
||||
3. **Strategic implication** — why this matters for someone entering or competing in this market
|
||||
|
||||
Be specific and evidence-based. Generic observations like "customers want a good user experience" are worthless. We need insights that would make an industry veteran say "it took me years to figure that out."
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Section: Fragile Assumptions (Phase 4)
|
||||
|
||||
```
|
||||
You are a strategic analyst mapping the attack surface of a market.
|
||||
|
||||
Research brief:
|
||||
{RESEARCH_BRIEF}
|
||||
|
||||
Source Dossier:
|
||||
{FULL_SOURCE_DOSSIER}
|
||||
|
||||
Prior analysis — Unspoken Insights:
|
||||
{PHASE_3_RESULTS}
|
||||
|
||||
Your task: Answer this question:
|
||||
|
||||
"What are the 3-5 assumptions this entire market is built on, and what would have to be true for each one to be wrong?"
|
||||
|
||||
Every market operates on a set of shared beliefs that nobody questions. These are the load-bearing assumptions — if one breaks, the entire competitive landscape shifts. Your job is to find them.
|
||||
|
||||
Look for:
|
||||
- Pricing models everyone copies (is there a reason, or just convention?)
|
||||
- Distribution channels everyone uses (what if a new channel emerges?)
|
||||
- Customer segments everyone targets (who is being ignored?)
|
||||
- Technology choices everyone makes (what if the tech shifts?)
|
||||
- Business models everyone follows (what if a different model works?)
|
||||
- Regulations everyone plans around (what if they change?)
|
||||
|
||||
For each assumption, return:
|
||||
1. **The assumption** — what everyone in this market believes
|
||||
2. **Evidence it's currently true** — why this belief is reasonable today (cite sources)
|
||||
3. **Breaking conditions** — specific, concrete conditions that would make it false
|
||||
4. **Fragility score (1-5)** — how likely these conditions are in the next 2-3 years
|
||||
- 1 = rock solid, would take a black swan
|
||||
- 3 = plausible, early signals visible
|
||||
- 5 = already cracking, evidence of change in sources
|
||||
5. **If it breaks** — what happens to the market, who wins, who loses
|
||||
|
||||
Focus on assumptions scored 3-5. Those are the real attack surfaces.
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Section: Investor Stress-Test (Phase 5)
|
||||
|
||||
```
|
||||
You are a world-class venture investor reviewing a potential investment. Your reputation depends on finding fatal flaws BEFORE writing a check. You've seen 10,000 pitches and killed 9,900 of them.
|
||||
|
||||
Research brief:
|
||||
{RESEARCH_BRIEF}
|
||||
|
||||
Source Dossier:
|
||||
{FULL_SOURCE_DOSSIER}
|
||||
|
||||
Prior analysis:
|
||||
- Unspoken Insights: {PHASE_3_RESULTS}
|
||||
- Fragile Assumptions: {PHASE_4_RESULTS}
|
||||
|
||||
Your task:
|
||||
|
||||
Step 1: Write 5 questions that would destroy this business idea. Not softballs — the questions that make founders sweat. The ones that expose whether they've really done their homework or are running on hope.
|
||||
|
||||
Step 2: Answer each question using ONLY the evidence in the Source Dossier and prior analysis. No hand-waving. If the evidence doesn't support a strong answer, say so.
|
||||
|
||||
For each of the 5 questions:
|
||||
1. **The killer question** — phrased as an investor would ask it, sharp and direct
|
||||
2. **The evidence-based answer** — using only our collected sources
|
||||
3. **Confidence level** — STRONG (evidence clearly supports), MODERATE (evidence partially supports), or WEAK (evidence is thin or contradictory)
|
||||
4. **Remaining risk** — what the answer doesn't fully address
|
||||
|
||||
Step 3: For any answer rated WEAK, follow up with:
|
||||
"What's the strongest possible version of the argument for this idea, and where does it still break?"
|
||||
|
||||
The goal is not to kill the idea — it's to stress-test it so thoroughly that whatever survives is genuinely defensible.
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Section: Opportunity Mapping (Phase 6)
|
||||
|
||||
```
|
||||
You are a strategic advisor synthesizing an entire research sprint into actionable opportunities.
|
||||
|
||||
Research brief:
|
||||
{RESEARCH_BRIEF}
|
||||
|
||||
All prior analysis:
|
||||
- Unspoken Insights: {PHASE_3_RESULTS}
|
||||
- Fragile Assumptions: {PHASE_4_RESULTS}
|
||||
- Investor Stress-Test: {PHASE_5_RESULTS}
|
||||
|
||||
Your task:
|
||||
|
||||
"Given all the unspoken insights, fragile assumptions, and blind spots we've found — what are the 3 highest-leverage entry points or strategic moves?"
|
||||
|
||||
For each opportunity:
|
||||
1. **The opportunity** — one clear sentence describing the strategic move
|
||||
2. **Why now** — what's changed (or changing) that makes this viable
|
||||
3. **Evidence** — specific findings from our research that support this
|
||||
4. **The moat** — what would make this defensible once established
|
||||
5. **Risk** — the biggest thing that could go wrong
|
||||
6. **Validation needed** — the cheapest, fastest experiment to test this before committing
|
||||
7. **Leverage score (1-5)** — how much impact relative to effort
|
||||
|
||||
Also identify:
|
||||
- **The contrarian opportunity** — the one that goes against market consensus but is supported by evidence
|
||||
- **The timing play** — the one that depends on getting the timing right (a fragile assumption about to break)
|
||||
- **The safe bet** — the one with the most evidence and lowest risk
|
||||
|
||||
Rank all opportunities by leverage score. Be honest about which ones are speculative vs. well-supported.
|
||||
```
|
||||
@@ -0,0 +1,188 @@
|
||||
# Source Gatherer — Prompt Templates
|
||||
|
||||
Use these templates when running Phase 2 source collection. Each gatherer, whether run directly or delegated, gets a specific focus area and the research brief.
|
||||
|
||||
## Search Tool Instructions
|
||||
|
||||
Include ONE of these blocks at the top of every gatherer prompt, depending on Exa availability:
|
||||
|
||||
### If Exa MCP is available:
|
||||
```
|
||||
SEARCH TOOLS: Use Exa MCP for all searches.
|
||||
- `mcp__exa__web_search_exa` — neural search, returns relevant results with snippets
|
||||
- `mcp__exa__crawling_exa` — crawl a URL to get full page content (use maxCharacters: 10000)
|
||||
- `mcp__exa__deep_researcher_start` + `mcp__exa__deep_researcher_check` — for comprehensive research queries
|
||||
```
|
||||
|
||||
### If Exa MCP is NOT available (fallback):
|
||||
```
|
||||
SEARCH TOOLS: Use the built-in web browsing tools available in the current Codex environment.
|
||||
- Use web search to find relevant pages and search variations.
|
||||
- Open the most relevant pages to read full content.
|
||||
- Preserve source URLs for every quote, data point, or claim you extract.
|
||||
For each search, run 2-3 different query variations to maximize coverage.
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Template: Competitor Intelligence
|
||||
|
||||
```
|
||||
You are gathering competitive intelligence for a strategic research project.
|
||||
|
||||
{SEARCH_TOOL_INSTRUCTIONS}
|
||||
|
||||
Research brief:
|
||||
{RESEARCH_BRIEF}
|
||||
|
||||
Your job: Find and analyze 5-8 competitor or key player websites in this market.
|
||||
|
||||
Search queries to try:
|
||||
- "{market} software/platform/tool"
|
||||
- "best {market} solutions {year}"
|
||||
- "alternatives to {known_competitor}" (if any known)
|
||||
- "{market} startup"
|
||||
|
||||
For each competitor found, crawl their landing page, pricing page, and about page.
|
||||
|
||||
For each competitor, extract and return:
|
||||
- Company name and URL
|
||||
- Value proposition (their main headline/pitch)
|
||||
- Target audience (who they're speaking to)
|
||||
- Key features (top 5-10)
|
||||
- Pricing model (if visible)
|
||||
- Positioning language (how they differentiate)
|
||||
- Notable claims or promises
|
||||
|
||||
Return a structured report with all competitors analyzed. Include direct quotes from their sites.
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Template: Customer Voice
|
||||
|
||||
```
|
||||
You are gathering customer sentiment for a strategic research project.
|
||||
|
||||
{SEARCH_TOOL_INSTRUCTIONS}
|
||||
|
||||
Research brief:
|
||||
{RESEARCH_BRIEF}
|
||||
|
||||
Your job: Find genuine customer opinions — complaints, praise, and unmet needs.
|
||||
|
||||
Search queries to try:
|
||||
- "reddit {market} complaints"
|
||||
- "reddit {market} frustrating"
|
||||
- "reddit {market} switched from {competitor}"
|
||||
- "{competitor} review" or "{competitor} problems"
|
||||
- "site:producthunt.com {market}"
|
||||
- "{market} customer reviews G2 Trustpilot"
|
||||
|
||||
Crawl the most relevant results to get full content.
|
||||
|
||||
Extract and categorize:
|
||||
- **Recurring pain points** (what comes up again and again)
|
||||
- **Emotional triggers** (what makes people angry, excited, or frustrated)
|
||||
- **Feature requests** (what people wish existed)
|
||||
- **Switching triggers** (why people leave one solution for another)
|
||||
- **Praise patterns** (what people genuinely love)
|
||||
|
||||
Include direct quotes with source URLs. Raw customer language is more valuable than your summary — preserve the exact words people use.
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Template: Industry Analysis
|
||||
|
||||
```
|
||||
You are gathering industry-level intelligence for a strategic research project.
|
||||
|
||||
{SEARCH_TOOL_INSTRUCTIONS}
|
||||
|
||||
Research brief:
|
||||
{RESEARCH_BRIEF}
|
||||
|
||||
Your job: Find broad industry context — market size, trends, expert analysis.
|
||||
|
||||
Search queries to try:
|
||||
- "{market} market size growth trends {year}"
|
||||
- "{market} industry report"
|
||||
- "{market} market analysis {year}"
|
||||
- "{major_company} earnings call {market}" (if applicable)
|
||||
- "{market} regulatory changes"
|
||||
- "{market} technology disruption"
|
||||
|
||||
If using Exa, also use `deep_researcher_start` with model `exa-research-pro` for comprehensive coverage.
|
||||
|
||||
Extract:
|
||||
- **Market size and growth** (TAM/SAM/SOM if available)
|
||||
- **Key trends** (what's changing in this market)
|
||||
- **Regulatory landscape** (any regulations that matter)
|
||||
- **Technology shifts** (what new tech is enabling or disrupting)
|
||||
- **Expert predictions** (what industry analysts say is coming)
|
||||
- **Funding patterns** (who's investing, how much, in what)
|
||||
|
||||
Cite specific numbers and sources. Vague claims like "the market is growing" without data are useless.
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Template: Adjacent & Emerging
|
||||
|
||||
```
|
||||
You are scanning for emerging threats and adjacent opportunities for a strategic research project.
|
||||
|
||||
{SEARCH_TOOL_INSTRUCTIONS}
|
||||
|
||||
Research brief:
|
||||
{RESEARCH_BRIEF}
|
||||
|
||||
Your job: Find what's coming next — new entrants, adjacent markets, and potential disruptors.
|
||||
|
||||
Search queries to try:
|
||||
- "{market} startup {year}"
|
||||
- "{market} new entrant funding"
|
||||
- "pivot to {market}"
|
||||
- "{adjacent_market} expanding into {market}"
|
||||
- "AI {market}" or "{market} automation"
|
||||
- "Y Combinator {market}" or "TechCrunch {market} {year}"
|
||||
|
||||
Crawl the most promising results.
|
||||
|
||||
Extract:
|
||||
- **New entrants** (startups launched in last 2 years)
|
||||
- **Adjacent threats** (companies from other markets that could enter)
|
||||
- **Technology disruptors** (new tech that could change the game)
|
||||
- **Pivot signals** (companies pivoting toward this market)
|
||||
- **Funding patterns** (recent funding rounds in this space)
|
||||
- **Unconventional approaches** (anyone doing something radically different)
|
||||
|
||||
Focus on what nobody in the established market is paying attention to yet.
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Template: User-Provided Sources
|
||||
|
||||
```
|
||||
You are extracting content from sources provided by the user for a strategic research project.
|
||||
|
||||
{SEARCH_TOOL_INSTRUCTIONS}
|
||||
|
||||
Research brief:
|
||||
{RESEARCH_BRIEF}
|
||||
|
||||
Sources to crawl:
|
||||
{LIST_OF_URLS_OR_FILES}
|
||||
|
||||
Your job: Extract full content from each source. For URLs, use crawling or page-open tools. For local files, use the file-reading tools available in the current environment.
|
||||
|
||||
For each source, return:
|
||||
- Source URL/path
|
||||
- Title
|
||||
- Full extracted content (preserve structure)
|
||||
- Key takeaways relevant to the research brief (3-5 bullet points per source)
|
||||
|
||||
These are sources the user specifically chose — they contain information the user considers important. Extract everything.
|
||||
```
|
||||
@@ -1,41 +0,0 @@
|
||||
---
|
||||
name: bun-best-practices
|
||||
description: Use when working in this repository with Bun scripts, dependency installs, tests, lockfiles, dev servers, Elysia API runtime, or frontend bundling decisions.
|
||||
---
|
||||
|
||||
# Bun Best Practices
|
||||
|
||||
This repo is Bun-native: Bun is the package manager, script runner, TypeScript/JSX runtime, test runner, API runtime, and frontend bundler unless a task has a specific compatibility constraint.
|
||||
|
||||
## Project Guidance
|
||||
|
||||
- Keep dependency declarations in `package.json`, exact resolution state in `bun.lock`, and Bun configuration in `bunfig.toml`. Do not add npm, Yarn, or pnpm lockfiles for normal work.
|
||||
- Prefer `bun run <script>` for repo scripts: `dev`, `dev:all`, `styles:build`, `web:dev`, `api:dev`, `build`, and `check`.
|
||||
- Let Bun execute `.ts`, `.tsx`, `.js`, and `.jsx` directly. Avoid `ts-node`, `tsx`, `node --loader`, or transpile-first flows unless an external tool requires them.
|
||||
- For the Elysia API, treat Bun runtime changes as production-sensitive: add smoke/load checks, watch RSS/native memory as well as JS heap, handle client disconnects for long-lived responses, keep monitoring visible, and preserve a rollback path for runtime upgrades.
|
||||
- Prefer Bun's built-in test runner for new simple TypeScript-first tests, but preserve Jest/Vitest when existing tests depend on their exact mocking, isolation, or DOM behavior.
|
||||
|
||||
## Quick Reference
|
||||
|
||||
| Task | Preferred command |
|
||||
| --- | --- |
|
||||
| Install/update deps | `bun install` |
|
||||
| Reproducible CI install | `bun ci` |
|
||||
| Run all dev surfaces | `bun run dev:all` |
|
||||
| Run API dev server | `bun run api:dev` |
|
||||
| Run web dev server | `bun run web:dev` |
|
||||
| Build | `bun run build` |
|
||||
| Check project | `bun run check` |
|
||||
| Run tests | `bun test` |
|
||||
| Restart on file changes | `bun --watch run <script>` |
|
||||
| Hot reload preserving global state | `bun --hot run <script>` |
|
||||
|
||||
`bun run` resolves package scripts first, then files, package binaries, and finally system commands. If a command name is ambiguous, prefer the explicit package script.
|
||||
|
||||
## Common Mistakes
|
||||
|
||||
- Putting watch flags after `run`: use `bun --watch run api:dev`, not `bun run --watch api:dev`.
|
||||
- Confusing `--watch` and `--hot`: `--watch` restarts the process; `--hot` soft reloads and preserves global state.
|
||||
- Using `bun install` in CI when reproducibility matters: use `bun ci` so the lockfile is frozen.
|
||||
- Adding Node-centric shims because TypeScript is present: Bun already executes TS/JSX directly.
|
||||
- Treating runtime adoption as risk-free: Bun is excellent for tooling and dev speed, but production runtime changes still need load/smoke coverage, memory monitoring, disconnect cleanup, and rollback.
|
||||
@@ -1,62 +0,0 @@
|
||||
---
|
||||
name: composition-patterns
|
||||
description: Use when writing, reviewing, or refactoring React component APIs that risk boolean prop proliferation, renderHeader/renderFooter-style slots, prop drilling, trapped local state, context-provider architecture, compound components, explicit variants, or React 19 ref/context composition patterns.
|
||||
---
|
||||
|
||||
# Composition Patterns
|
||||
|
||||
## Overview
|
||||
|
||||
Apply scalable React composition patterns from Vercel's `composition-patterns`
|
||||
skill, adapted for this Next.js/FSD repository. Prefer explicit composed APIs
|
||||
over configuration-heavy components, and keep reusable UI parts decoupled from
|
||||
state implementations.
|
||||
|
||||
## Workflow
|
||||
|
||||
1. Identify whether the component is becoming a mode switcher.
|
||||
Look for multiple boolean props, conditional branches that choose whole UI
|
||||
regions, `renderHeader`/`renderFooter` props, or impossible prop
|
||||
combinations.
|
||||
2. Split behavior into explicit variants when the rendered structure differs.
|
||||
Prefer names such as `ThreadComposer`, `EditComposer`, or
|
||||
`ForwardComposer` over one `Composer` with `isThread`, `isEditing`, and
|
||||
`isForwarding`.
|
||||
3. Extract shared pieces into compound components when consumers need to
|
||||
arrange the parts themselves. Use `Root`/`Provider`, `Frame`, `Header`,
|
||||
`Body`, `Footer`, `Trigger`, `Content`, `Action`, or domain-specific names
|
||||
that fit the existing component.
|
||||
4. Lift shared state into a provider boundary when siblings or custom outer UI
|
||||
need the same state/actions. Keep visual nesting separate from state access:
|
||||
components only need to be inside the provider, not inside the same DOM box.
|
||||
5. Define a context contract with `state`, `actions`, and `meta` when multiple
|
||||
providers can drive the same UI. UI subcomponents consume the contract, while
|
||||
providers decide whether state comes from local hooks, server-synced data,
|
||||
forms, or feature-specific stores.
|
||||
6. In this React 19 repo, pass `ref` as a normal prop and use `use(Context)` for
|
||||
context reads where the surrounding codebase allows it. Preserve existing
|
||||
conventions if a nearby component has not migrated yet.
|
||||
|
||||
## Decision Rules
|
||||
|
||||
- Do not add a boolean prop to control a large behavior branch until checking
|
||||
whether an explicit variant or child composition would make the state space
|
||||
clearer.
|
||||
- Use children for static structure composition. Keep render props for cases
|
||||
where the parent must pass item data, measurements, or callback-local state
|
||||
back into the child.
|
||||
- Keep providers as the only layer that knows a concrete state implementation.
|
||||
Subcomponents should not import feature stores or synchronization hooks unless
|
||||
they are provider components.
|
||||
- Avoid prop drilling through compound components. Put shared state/actions in a
|
||||
typed context and expose narrow subcomponents.
|
||||
- Keep FSD boundaries intact: shared compound UI belongs under `src/shared/ui`;
|
||||
feature-specific variants and providers belong in the appropriate feature,
|
||||
entity, widget, or page layer.
|
||||
|
||||
## Reference
|
||||
|
||||
Read `references/rules.md` when you need examples, a review checklist, or the
|
||||
upstream rule inventory. It summarizes all files from:
|
||||
`https://github.com/vercel-labs/agent-skills/tree/main/skills/composition-patterns`
|
||||
at commit `ce3e64e468f8fa09a2d075d102771838061fdac0`.
|
||||
@@ -1,4 +0,0 @@
|
||||
interface:
|
||||
display_name: "Composition Patterns"
|
||||
short_description: "Apply scalable React composition patterns."
|
||||
default_prompt: "Use composition patterns to refactor or design a React component API."
|
||||
@@ -1,91 +0,0 @@
|
||||
# React Composition Rules
|
||||
|
||||
This reference distills the upstream Vercel `composition-patterns` skill. The
|
||||
upstream directory was inspected as a whole: `SKILL.md`, `README.md`,
|
||||
`metadata.json`, generated `AGENTS.md`, `_sections.md`, `_template.md`, and all
|
||||
rule files under `rules/`.
|
||||
|
||||
## Rule Inventory
|
||||
|
||||
| Area | Rule | Use it to |
|
||||
| --- | --- | --- |
|
||||
| Architecture | Avoid boolean prop proliferation | Replace mode booleans with explicit composed variants. |
|
||||
| Architecture | Use compound components | Let consumers arrange subcomponents that share context. |
|
||||
| State | Decouple state management from UI | Keep concrete hooks/stores inside providers. |
|
||||
| State | Define generic context interfaces | Share UI across providers using `state`, `actions`, `meta`. |
|
||||
| State | Lift state into providers | Let outer/sibling components access composer-like state without refs or effects. |
|
||||
| Patterns | Create explicit component variants | Make each mode self-documenting and impossible-state-free. |
|
||||
| Patterns | Prefer children over render props | Use children for structure; reserve render props for data callbacks. |
|
||||
| React 19 | Ref and context API changes | Use ref as a prop and `use(Context)` when the codebase is React 19+. |
|
||||
|
||||
## Core Principles
|
||||
|
||||
- Composition over configuration: let consumers assemble behavior from parts
|
||||
instead of adding props for every mode.
|
||||
- State belongs at the provider boundary when more than one child or sibling
|
||||
needs it.
|
||||
- Compound internals should read shared context, not receive long prop chains.
|
||||
- Explicit variants are clearer than a single component with many conditional
|
||||
branches.
|
||||
|
||||
## Refactoring Checklist
|
||||
|
||||
1. Count behavior flags and conditional branches. Two or more mode booleans are
|
||||
a strong signal to split variants.
|
||||
2. Identify shared primitives. Extract the stable pieces first: frame, input,
|
||||
header, footer, trigger, content, action, item, or slot-like sections.
|
||||
3. Decide the provider boundary. Put it around every component that needs the
|
||||
shared state, even if some of those components are visually outside the main
|
||||
frame.
|
||||
4. Define the context shape before wiring UI. Prefer:
|
||||
|
||||
```ts
|
||||
interface ComponentContextValue {
|
||||
state: ComponentState
|
||||
actions: ComponentActions
|
||||
meta: ComponentMeta
|
||||
}
|
||||
```
|
||||
|
||||
5. Move implementation-specific hooks into provider variants. For example,
|
||||
`LocalComposerProvider`, `ChannelComposerProvider`, and
|
||||
`EditComposerProvider` can implement the same UI contract.
|
||||
6. Replace `renderX` props with children when the consumer is only placing
|
||||
static structure.
|
||||
7. Keep render props when the parent must provide data to each render, such as
|
||||
list items, indices, or measured layout values.
|
||||
8. For React 19 code, avoid adding new `forwardRef` wrappers unless compatibility
|
||||
with React 18 or an existing library API requires it.
|
||||
|
||||
## Review Smells
|
||||
|
||||
- A component accepts several props named `is*`, `show*`, `has*`, or `mode` and
|
||||
uses them to render different major sections.
|
||||
- A caller can pass contradictory props, such as `isEditing` and `isForwarding`.
|
||||
- A reusable UI component imports a feature store, route-specific hook, or sync
|
||||
mechanism directly.
|
||||
- State is copied upward through `useEffect` solely so another sibling can read
|
||||
it.
|
||||
- A submit button reads state from a ref because the state is trapped inside a
|
||||
child component.
|
||||
- `renderHeader`, `renderFooter`, or `renderActions` props are used only to place
|
||||
static nodes.
|
||||
|
||||
## Repo Adaptation
|
||||
|
||||
- Put generic primitives in `src/shared/ui/<Component>/` with the repo's usual
|
||||
source, SCSS module, test, story, and barrel layout.
|
||||
- Keep feature-specific provider variants out of `shared` if they import
|
||||
feature/entity/page state.
|
||||
- Export public compound pieces through `index.ts` instead of deep imports.
|
||||
- Coordinate with `react-best-practices` for performance, Server Component
|
||||
boundaries, serialization, and client bundle impact.
|
||||
- Coordinate with `storybook-ai-best-practices` when adding stories so each
|
||||
compound part, variant, and state has focused examples.
|
||||
|
||||
## Source Notes
|
||||
|
||||
The upstream skill is version `1.0.0`, dated January 2026, and references React
|
||||
documentation for context and the `use` API. Its generated `AGENTS.md` is a
|
||||
compiled form of the individual rules, so prefer this distilled reference for
|
||||
day-to-day work and consult the upstream repo only when refreshing the skill.
|
||||
@@ -1,140 +0,0 @@
|
||||
---
|
||||
name: elysia-best-practices
|
||||
description: Use when writing, reviewing, or refactoring Elysia server code in this repository, including route handlers, schemas, response statuses, lifecycle hooks, plugins, OpenAPI docs, health checks, render API endpoints, and queue-facing API behavior.
|
||||
---
|
||||
|
||||
# Elysia Best Practices
|
||||
|
||||
## Overview
|
||||
|
||||
Apply current Elysia guidance to this Bun Remotion rendering service while
|
||||
preserving its API contract: `/api/render` can enqueue async jobs, render
|
||||
synchronously, report BullMQ status, cancel jobs, and expose health checks.
|
||||
|
||||
## Workflow
|
||||
|
||||
1. Fetch current Elysia docs first with Context7. This repo currently uses
|
||||
`elysia` `1.4.27`, `@elysiajs/openapi` `1.4.14`, and
|
||||
`@elysiajs/swagger` `1.3.1`; compare docs against those packages before
|
||||
adopting examples that use newer `@elysia/openapi` imports.
|
||||
2. Identify the layer being changed:
|
||||
- HTTP entrypoint: `server/index.ts`
|
||||
- Shared request schemas: `server/types/DocumentSchema.ts`,
|
||||
`server/types/CaptionStyleSchema.ts`
|
||||
- Queue behavior: `server/services/render_queue.ts`
|
||||
- Rendering and cleanup: `server/services/render_video.ts`
|
||||
- S3/webhooks/config: `server/services/s3.ts`,
|
||||
`server/services/webhook.ts`, `server/config.ts`
|
||||
3. Keep Elysia routes thin. Validate and shape HTTP inputs at the route, then
|
||||
delegate rendering, queue, upload, and webhook work to services.
|
||||
4. Verify with `bun run lint` and a focused smoke test through `bun run server`,
|
||||
`/api/health`, and the affected `/api/render` path.
|
||||
|
||||
## Project Map
|
||||
|
||||
- Runtime: Bun with strict TypeScript and path aliases from `tsconfig.json`.
|
||||
- Server root: `new Elysia({ prefix: "/api" })` in `server/index.ts`.
|
||||
- Current endpoints:
|
||||
- `POST /api/render`: async queue when `callbackUrl` is present; synchronous
|
||||
render/upload fallback otherwise.
|
||||
- `GET /api/render/:renderId`: BullMQ job state and progress.
|
||||
- `DELETE /api/render/:renderId`: cancellation.
|
||||
- `GET /api/health`: liveness response.
|
||||
- Existing schemas use Elysia `t` and `Static`; reuse this style instead of
|
||||
introducing Zod, Valibot, or ad hoc runtime checks.
|
||||
|
||||
## Route Contracts
|
||||
|
||||
- Define schemas for `body`, `params`, `query`, `headers`, and `response`.
|
||||
Elysia infers handler types from schemas, so avoid duplicate TypeScript
|
||||
interfaces unless they are exported from `Static<typeof Schema>`.
|
||||
- For route responses with multiple statuses, define `response` by status code
|
||||
and return `status(code, body)` from the handler. Prefer this for new code over
|
||||
mutating `set.status`; current docs call `set.status` legacy and it cannot
|
||||
validate response types as precisely.
|
||||
- Preserve existing API payload field names unless intentionally migrating a
|
||||
client contract: `renderId`, `status`, `progress_pct`, `output_path`,
|
||||
`callback_delivered`, and `error`.
|
||||
- Use literal unions for finite render states and style values. Keep captions
|
||||
and transcription schemas reusable in `server/types/`, not embedded inside
|
||||
handlers.
|
||||
- Validate URL-like inputs that leave the service boundary. For new fields such
|
||||
as callback or source URLs, prefer a schema-level constraint or a small service
|
||||
validator before queueing work.
|
||||
|
||||
## Status And Errors
|
||||
|
||||
- Use the handler context `status()` function for expected outcomes:
|
||||
`return status(202, { renderId, status: "queued" })` and
|
||||
`return status(404, result)`.
|
||||
- Use `onError` for cross-cutting logging and sanitized error responses, and
|
||||
register it before routes it must affect. Do not leak S3 credentials, signed
|
||||
URLs, local output paths, full Remotion CLI logs, or Redis connection details.
|
||||
- Validation failures normally return 422. In production, Elysia omits detailed
|
||||
validation internals by default; keep that behavior unless debugging explicitly
|
||||
requires a temporary override.
|
||||
- When adding typed domain errors, register classes with `.error()` and narrow in
|
||||
`.onError()`. For one route only, use a local route `error` hook.
|
||||
|
||||
## Lifecycle And Plugins
|
||||
|
||||
- Hook order matters. Interceptor hooks apply only to routes registered after
|
||||
them; place auth, tracing, error mapping, CORS, or request logging before the
|
||||
routes they should cover.
|
||||
- Elysia plugin lifecycles and schemas are encapsulated by default. Use `local`,
|
||||
`scoped`, or `global` intentionally when extracting route groups or shared
|
||||
guards, especially if a guard should affect parent `/api` routes.
|
||||
- Prefer `resolve` for per-request values that depend on validated data, such as
|
||||
a parsed render ID, normalized callback URL, or tenant/folder value. Use
|
||||
`derive` for request-derived context before validation only when validation is
|
||||
not needed first.
|
||||
- Use `decorate` for stable shared services or helpers, not request-specific
|
||||
mutable data. Avoid putting queue job state in Elysia `store`; BullMQ and Redis
|
||||
are the source of truth.
|
||||
- If route count grows, extract plugins by concern, for example `renderRoutes`,
|
||||
`healthRoutes`, and `openApiPlugin`, then mount them under the existing
|
||||
prefixed app.
|
||||
|
||||
## OpenAPI
|
||||
|
||||
- If exposing docs, prefer one OpenAPI integration and make it match installed
|
||||
packages. This repo already has `@elysiajs/openapi` and `@elysiajs/swagger`;
|
||||
do not add `@elysia/openapi` without an intentional dependency migration.
|
||||
- Add `detail` metadata for public endpoints: tags, summary, description, and
|
||||
response examples where helpful. Keep docs accurate by defining runtime
|
||||
schemas for request and response shapes.
|
||||
- Treat render endpoints as operational API, not demo routes. Document async
|
||||
queue behavior, callback delivery, cancellation semantics, and sync fallback
|
||||
separately.
|
||||
|
||||
## Service Boundaries
|
||||
|
||||
- Do not start extra BullMQ workers from route modules. The current server starts
|
||||
one worker at process boot; keep worker lifecycle explicit and graceful.
|
||||
- Keep cleanup in `finally` when route code creates local render outputs. Do not
|
||||
leave generated videos or props files behind after uploads or failures.
|
||||
- Avoid blocking request handlers with long synchronous work unless preserving
|
||||
the existing no-`callbackUrl` sync fallback. Prefer queueing for new expensive
|
||||
render operations.
|
||||
- Keep env requirements in `server/config.ts` and `.env.example` together. Never
|
||||
hardcode credentials, bucket names, Redis URLs, or public host assumptions in
|
||||
Elysia handlers.
|
||||
|
||||
## Validation
|
||||
|
||||
- Always run `bun run lint` after TypeScript/Elysia changes.
|
||||
- For schema or status changes, smoke invalid requests and expected non-200
|
||||
responses, not only the happy path.
|
||||
- For queue-facing changes, smoke `POST /api/render` with `callbackUrl`,
|
||||
`GET /api/render/:renderId`, and `DELETE /api/render/:renderId`.
|
||||
- For docs changes, verify the generated OpenAPI page/spec if the plugin is
|
||||
mounted.
|
||||
|
||||
## Source Anchors
|
||||
|
||||
- Validation and response schemas: https://elysiajs.com/tutorial/getting-started/validation/
|
||||
- Handler context and `status()`: https://elysiajs.com/essential/handler
|
||||
- Lifecycle and hook ordering: https://elysiajs.com/essential/life-cycle
|
||||
- Error handling: https://elysiajs.com/patterns/error-handling
|
||||
- Encapsulation, scopes, and guards: https://elysiajs.com/tutorial/getting-started/encapsulation/
|
||||
- OpenAPI patterns: https://elysiajs.com/patterns/openapi
|
||||
@@ -1,4 +0,0 @@
|
||||
interface:
|
||||
display_name: "Elysia Best Practices"
|
||||
short_description: "Guide Elysia API changes in this service."
|
||||
default_prompt: "Use $elysia-best-practices when changing the Elysia API, schemas, route handlers, hooks, or OpenAPI docs in this service."
|
||||
@@ -1,31 +0,0 @@
|
||||
---
|
||||
name: react-best-practices
|
||||
description: Use when writing, reviewing, or refactoring React/Next.js code in this repository, especially components, App Router pages, Server Actions, data fetching, bundle optimization, render performance, hydration, or UI responsiveness work.
|
||||
---
|
||||
|
||||
# React Best Practices
|
||||
|
||||
## Overview
|
||||
|
||||
Apply Vercel's React and Next.js performance guidance to this repository. The upstream skill was inspected as a full directory, including `SKILL.md`, `README.md`, `metadata.json`, the generated `AGENTS.md`, and all source rule files under `rules/`.
|
||||
|
||||
## How to Use
|
||||
|
||||
Start with the highest-impact category that matches the task:
|
||||
|
||||
1. **Eliminating Waterfalls:** parallelize independent async work, defer awaits until needed, start promises early, and use Suspense boundaries deliberately.
|
||||
2. **Bundle Size Optimization:** avoid broad imports where Next cannot optimize them, use `next/dynamic` for heavy UI, defer third-party client libraries, and keep dynamic paths statically analyzable.
|
||||
3. **Server-Side Performance:** authenticate Server Actions like public API endpoints, avoid mutable request-scoped module state, minimize RSC-to-client serialization, dedupe per request with `React.cache()`, and hoist static I/O.
|
||||
4. **Client Data & Rendering:** dedupe global listeners and requests, use passive scroll listeners, avoid derived-state effects, narrow effect dependencies, move interaction logic into handlers, and avoid inline component definitions.
|
||||
5. **Hot Path JavaScript:** use early returns, `Set`/`Map` lookups, index maps, cached property reads, immutable `toSorted()`, and combined iterations only where the path is performance-sensitive.
|
||||
|
||||
For this Next/FSD repo, preserve the existing layer boundaries and public `index.ts` APIs while applying these patterns.
|
||||
|
||||
## References
|
||||
|
||||
- Full compiled guide: `references/vercel-react-best-practices-full.md`
|
||||
- Source rules: `references/rules/*.md`
|
||||
- Rule categories and impact: `references/rules/_sections.md`
|
||||
- Upstream metadata and maintenance notes: `references/upstream/`
|
||||
|
||||
Read only the relevant rule files for the task. Use the compiled guide when a broader review needs cross-category context or examples.
|
||||
@@ -1,4 +0,0 @@
|
||||
interface:
|
||||
display_name: "React Best Practices"
|
||||
short_description: "Apply Vercel React and Next.js performance guidance."
|
||||
default_prompt: "Use this skill when writing, reviewing, or refactoring React/Next.js code in this repository."
|
||||
@@ -1,46 +0,0 @@
|
||||
# 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.
|
||||
@@ -1,28 +0,0 @@
|
||||
---
|
||||
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)
|
||||
@@ -1,56 +0,0 @@
|
||||
---
|
||||
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)
|
||||
@@ -1,55 +0,0 @@
|
||||
---
|
||||
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.
|
||||
@@ -1,42 +0,0 @@
|
||||
---
|
||||
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)
|
||||
@@ -1,39 +0,0 @@
|
||||
---
|
||||
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])
|
||||
}
|
||||
```
|
||||
@@ -1,38 +0,0 @@
|
||||
---
|
||||
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).
|
||||
-37
@@ -1,37 +0,0 @@
|
||||
---
|
||||
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.
|
||||
@@ -1,82 +0,0 @@
|
||||
---
|
||||
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).
|
||||
@@ -1,51 +0,0 @@
|
||||
---
|
||||
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)
|
||||
@@ -1,28 +0,0 @@
|
||||
---
|
||||
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()
|
||||
])
|
||||
```
|
||||
@@ -1,99 +0,0 @@
|
||||
---
|
||||
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.
|
||||
@@ -1,63 +0,0 @@
|
||||
---
|
||||
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/)
|
||||
@@ -1,60 +0,0 @@
|
||||
---
|
||||
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)
|
||||
@@ -1,31 +0,0 @@
|
||||
---
|
||||
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.
|
||||
@@ -1,49 +0,0 @@
|
||||
---
|
||||
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>
|
||||
)
|
||||
}
|
||||
```
|
||||
@@ -1,35 +0,0 @@
|
||||
---
|
||||
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} />
|
||||
}
|
||||
```
|
||||
@@ -1,50 +0,0 @@
|
||||
---
|
||||
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.
|
||||
@@ -1,74 +0,0 @@
|
||||
---
|
||||
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', () => { /* ... */ })
|
||||
// ...
|
||||
}
|
||||
```
|
||||
@@ -1,71 +0,0 @@
|
||||
---
|
||||
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.
|
||||
-48
@@ -1,48 +0,0 @@
|
||||
---
|
||||
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()`.
|
||||
@@ -1,56 +0,0 @@
|
||||
---
|
||||
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)
|
||||
@@ -1,107 +0,0 @@
|
||||
---
|
||||
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.
|
||||
@@ -1,80 +0,0 @@
|
||||
---
|
||||
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)
|
||||
@@ -1,28 +0,0 @@
|
||||
---
|
||||
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)
|
||||
}
|
||||
```
|
||||
@@ -1,70 +0,0 @@
|
||||
---
|
||||
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()
|
||||
}
|
||||
})
|
||||
```
|
||||
@@ -1,32 +0,0 @@
|
||||
---
|
||||
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)
|
||||
}
|
||||
```
|
||||
@@ -1,50 +0,0 @@
|
||||
---
|
||||
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 }
|
||||
}
|
||||
```
|
||||
@@ -1,60 +0,0 @@
|
||||
---
|
||||
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
|
||||
@@ -1,45 +0,0 @@
|
||||
---
|
||||
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
|
||||
```
|
||||
@@ -1,37 +0,0 @@
|
||||
---
|
||||
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.
|
||||
@@ -1,49 +0,0 @@
|
||||
---
|
||||
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
|
||||
@@ -1,82 +0,0 @@
|
||||
---
|
||||
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.
|
||||
@@ -1,105 +0,0 @@
|
||||
---
|
||||
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
|
||||
@@ -1,24 +0,0 @@
|
||||
---
|
||||
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))
|
||||
```
|
||||
@@ -1,57 +0,0 @@
|
||||
---
|
||||
title: Use toSorted() Instead of sort() for Immutability
|
||||
impact: MEDIUM-HIGH
|
||||
impactDescription: prevents mutation bugs in React state
|
||||
tags: javascript, arrays, immutability, react, state, mutation
|
||||
---
|
||||
|
||||
## Use toSorted() Instead of sort() for Immutability
|
||||
|
||||
`.sort()` mutates the array in place, which can cause bugs with React state and props. Use `.toSorted()` to create a new sorted array without mutation.
|
||||
|
||||
**Incorrect (mutates original array):**
|
||||
|
||||
```typescript
|
||||
function UserList({ users }: { users: User[] }) {
|
||||
// Mutates the users prop array!
|
||||
const sorted = useMemo(
|
||||
() => users.sort((a, b) => a.name.localeCompare(b.name)),
|
||||
[users]
|
||||
)
|
||||
return <div>{sorted.map(renderUser)}</div>
|
||||
}
|
||||
```
|
||||
|
||||
**Correct (creates new array):**
|
||||
|
||||
```typescript
|
||||
function UserList({ users }: { users: User[] }) {
|
||||
// Creates new sorted array, original unchanged
|
||||
const sorted = useMemo(
|
||||
() => users.toSorted((a, b) => a.name.localeCompare(b.name)),
|
||||
[users]
|
||||
)
|
||||
return <div>{sorted.map(renderUser)}</div>
|
||||
}
|
||||
```
|
||||
|
||||
**Why this matters in React:**
|
||||
|
||||
1. Props/state mutations break React's immutability model - React expects props and state to be treated as read-only
|
||||
2. Causes stale closure bugs - Mutating arrays inside closures (callbacks, effects) can lead to unexpected behavior
|
||||
|
||||
**Browser support (fallback for older browsers):**
|
||||
|
||||
`.toSorted()` is available in all modern browsers (Chrome 110+, Safari 16+, Firefox 115+, Node.js 20+). For older environments, use spread operator:
|
||||
|
||||
```typescript
|
||||
// Fallback for older browsers
|
||||
const sorted = [...items].sort((a, b) => a.value - b.value)
|
||||
```
|
||||
|
||||
**Other immutable array methods:**
|
||||
|
||||
- `.toSorted()` - immutable sort
|
||||
- `.toReversed()` - immutable reverse
|
||||
- `.toSpliced()` - immutable splice
|
||||
- `.with()` - immutable element replacement
|
||||
@@ -1,26 +0,0 @@
|
||||
---
|
||||
title: Use Activity Component for Show/Hide
|
||||
impact: MEDIUM
|
||||
impactDescription: preserves state/DOM
|
||||
tags: rendering, activity, visibility, state-preservation
|
||||
---
|
||||
|
||||
## Use Activity Component for Show/Hide
|
||||
|
||||
Use React's `<Activity>` to preserve state/DOM for expensive components that frequently toggle visibility.
|
||||
|
||||
**Usage:**
|
||||
|
||||
```tsx
|
||||
import { Activity } from 'react'
|
||||
|
||||
function Dropdown({ isOpen }: Props) {
|
||||
return (
|
||||
<Activity mode={isOpen ? 'visible' : 'hidden'}>
|
||||
<ExpensiveMenu />
|
||||
</Activity>
|
||||
)
|
||||
}
|
||||
```
|
||||
|
||||
Avoids expensive re-renders and state loss.
|
||||
@@ -1,47 +0,0 @@
|
||||
---
|
||||
title: Animate SVG Wrapper Instead of SVG Element
|
||||
impact: LOW
|
||||
impactDescription: enables hardware acceleration
|
||||
tags: rendering, svg, css, animation, performance
|
||||
---
|
||||
|
||||
## Animate SVG Wrapper Instead of SVG Element
|
||||
|
||||
Many browsers don't have hardware acceleration for CSS3 animations on SVG elements. Wrap SVG in a `<div>` and animate the wrapper instead.
|
||||
|
||||
**Incorrect (animating SVG directly - no hardware acceleration):**
|
||||
|
||||
```tsx
|
||||
function LoadingSpinner() {
|
||||
return (
|
||||
<svg
|
||||
className="animate-spin"
|
||||
width="24"
|
||||
height="24"
|
||||
viewBox="0 0 24 24"
|
||||
>
|
||||
<circle cx="12" cy="12" r="10" stroke="currentColor" />
|
||||
</svg>
|
||||
)
|
||||
}
|
||||
```
|
||||
|
||||
**Correct (animating wrapper div - hardware accelerated):**
|
||||
|
||||
```tsx
|
||||
function LoadingSpinner() {
|
||||
return (
|
||||
<div className="animate-spin">
|
||||
<svg
|
||||
width="24"
|
||||
height="24"
|
||||
viewBox="0 0 24 24"
|
||||
>
|
||||
<circle cx="12" cy="12" r="10" stroke="currentColor" />
|
||||
</svg>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
```
|
||||
|
||||
This applies to all CSS transforms and transitions (`transform`, `opacity`, `translate`, `scale`, `rotate`). The wrapper div allows browsers to use GPU acceleration for smoother animations.
|
||||
@@ -1,40 +0,0 @@
|
||||
---
|
||||
title: Use Explicit Conditional Rendering
|
||||
impact: LOW
|
||||
impactDescription: prevents rendering 0 or NaN
|
||||
tags: rendering, conditional, jsx, falsy-values
|
||||
---
|
||||
|
||||
## Use Explicit Conditional Rendering
|
||||
|
||||
Use explicit ternary operators (`? :`) instead of `&&` for conditional rendering when the condition can be `0`, `NaN`, or other falsy values that render.
|
||||
|
||||
**Incorrect (renders "0" when count is 0):**
|
||||
|
||||
```tsx
|
||||
function Badge({ count }: { count: number }) {
|
||||
return (
|
||||
<div>
|
||||
{count && <span className="badge">{count}</span>}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
// When count = 0, renders: <div>0</div>
|
||||
// When count = 5, renders: <div><span class="badge">5</span></div>
|
||||
```
|
||||
|
||||
**Correct (renders nothing when count is 0):**
|
||||
|
||||
```tsx
|
||||
function Badge({ count }: { count: number }) {
|
||||
return (
|
||||
<div>
|
||||
{count > 0 ? <span className="badge">{count}</span> : null}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
// When count = 0, renders: <div></div>
|
||||
// When count = 5, renders: <div><span class="badge">5</span></div>
|
||||
```
|
||||
@@ -1,38 +0,0 @@
|
||||
---
|
||||
title: CSS content-visibility for Long Lists
|
||||
impact: HIGH
|
||||
impactDescription: faster initial render
|
||||
tags: rendering, css, content-visibility, long-lists
|
||||
---
|
||||
|
||||
## CSS content-visibility for Long Lists
|
||||
|
||||
Apply `content-visibility: auto` to defer off-screen rendering.
|
||||
|
||||
**CSS:**
|
||||
|
||||
```css
|
||||
.message-item {
|
||||
content-visibility: auto;
|
||||
contain-intrinsic-size: 0 80px;
|
||||
}
|
||||
```
|
||||
|
||||
**Example:**
|
||||
|
||||
```tsx
|
||||
function MessageList({ messages }: { messages: Message[] }) {
|
||||
return (
|
||||
<div className="overflow-y-auto h-screen">
|
||||
{messages.map(msg => (
|
||||
<div key={msg.id} className="message-item">
|
||||
<Avatar user={msg.author} />
|
||||
<div>{msg.content}</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
```
|
||||
|
||||
For 1000 messages, browser skips layout/paint for ~990 off-screen items (10× faster initial render).
|
||||
@@ -1,46 +0,0 @@
|
||||
---
|
||||
title: Hoist Static JSX Elements
|
||||
impact: LOW
|
||||
impactDescription: avoids re-creation
|
||||
tags: rendering, jsx, static, optimization
|
||||
---
|
||||
|
||||
## Hoist Static JSX Elements
|
||||
|
||||
Extract static JSX outside components to avoid re-creation.
|
||||
|
||||
**Incorrect (recreates element every render):**
|
||||
|
||||
```tsx
|
||||
function LoadingSkeleton() {
|
||||
return <div className="animate-pulse h-20 bg-gray-200" />
|
||||
}
|
||||
|
||||
function Container() {
|
||||
return (
|
||||
<div>
|
||||
{loading && <LoadingSkeleton />}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
```
|
||||
|
||||
**Correct (reuses same element):**
|
||||
|
||||
```tsx
|
||||
const loadingSkeleton = (
|
||||
<div className="animate-pulse h-20 bg-gray-200" />
|
||||
)
|
||||
|
||||
function Container() {
|
||||
return (
|
||||
<div>
|
||||
{loading && loadingSkeleton}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
```
|
||||
|
||||
This is especially helpful for large and static SVG nodes, which can be expensive to recreate on every render.
|
||||
|
||||
**Note:** If your project has [React Compiler](https://react.dev/learn/react-compiler) enabled, the compiler automatically hoists static JSX elements and optimizes component re-renders, making manual hoisting unnecessary.
|
||||
-82
@@ -1,82 +0,0 @@
|
||||
---
|
||||
title: Prevent Hydration Mismatch Without Flickering
|
||||
impact: MEDIUM
|
||||
impactDescription: avoids visual flicker and hydration errors
|
||||
tags: rendering, ssr, hydration, localStorage, flicker
|
||||
---
|
||||
|
||||
## Prevent Hydration Mismatch Without Flickering
|
||||
|
||||
When rendering content that depends on client-side storage (localStorage, cookies), avoid both SSR breakage and post-hydration flickering by injecting a synchronous script that updates the DOM before React hydrates.
|
||||
|
||||
**Incorrect (breaks SSR):**
|
||||
|
||||
```tsx
|
||||
function ThemeWrapper({ children }: { children: ReactNode }) {
|
||||
// localStorage is not available on server - throws error
|
||||
const theme = localStorage.getItem('theme') || 'light'
|
||||
|
||||
return (
|
||||
<div className={theme}>
|
||||
{children}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
```
|
||||
|
||||
Server-side rendering will fail because `localStorage` is undefined.
|
||||
|
||||
**Incorrect (visual flickering):**
|
||||
|
||||
```tsx
|
||||
function ThemeWrapper({ children }: { children: ReactNode }) {
|
||||
const [theme, setTheme] = useState('light')
|
||||
|
||||
useEffect(() => {
|
||||
// Runs after hydration - causes visible flash
|
||||
const stored = localStorage.getItem('theme')
|
||||
if (stored) {
|
||||
setTheme(stored)
|
||||
}
|
||||
}, [])
|
||||
|
||||
return (
|
||||
<div className={theme}>
|
||||
{children}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
```
|
||||
|
||||
Component first renders with default value (`light`), then updates after hydration, causing a visible flash of incorrect content.
|
||||
|
||||
**Correct (no flicker, no hydration mismatch):**
|
||||
|
||||
```tsx
|
||||
function ThemeWrapper({ children }: { children: ReactNode }) {
|
||||
return (
|
||||
<>
|
||||
<div id="theme-wrapper">
|
||||
{children}
|
||||
</div>
|
||||
<script
|
||||
dangerouslySetInnerHTML={{
|
||||
__html: `
|
||||
(function() {
|
||||
try {
|
||||
var theme = localStorage.getItem('theme') || 'light';
|
||||
var el = document.getElementById('theme-wrapper');
|
||||
if (el) el.className = theme;
|
||||
} catch (e) {}
|
||||
})();
|
||||
`,
|
||||
}}
|
||||
/>
|
||||
</>
|
||||
)
|
||||
}
|
||||
```
|
||||
|
||||
The inline script executes synchronously before showing the element, ensuring the DOM already has the correct value. No flickering, no hydration mismatch.
|
||||
|
||||
This pattern is especially useful for theme toggles, user preferences, authentication states, and any client-only data that should render immediately without flashing default values.
|
||||
-30
@@ -1,30 +0,0 @@
|
||||
---
|
||||
title: Suppress Expected Hydration Mismatches
|
||||
impact: LOW-MEDIUM
|
||||
impactDescription: avoids noisy hydration warnings for known differences
|
||||
tags: rendering, hydration, ssr, nextjs
|
||||
---
|
||||
|
||||
## Suppress Expected Hydration Mismatches
|
||||
|
||||
In SSR frameworks (e.g., Next.js), some values are intentionally different on server vs client (random IDs, dates, locale/timezone formatting). For these *expected* mismatches, wrap the dynamic text in an element with `suppressHydrationWarning` to prevent noisy warnings. Do not use this to hide real bugs. Don’t overuse it.
|
||||
|
||||
**Incorrect (known mismatch warnings):**
|
||||
|
||||
```tsx
|
||||
function Timestamp() {
|
||||
return <span>{new Date().toLocaleString()}</span>
|
||||
}
|
||||
```
|
||||
|
||||
**Correct (suppress expected mismatch only):**
|
||||
|
||||
```tsx
|
||||
function Timestamp() {
|
||||
return (
|
||||
<span suppressHydrationWarning>
|
||||
{new Date().toLocaleString()}
|
||||
</span>
|
||||
)
|
||||
}
|
||||
```
|
||||
@@ -1,85 +0,0 @@
|
||||
---
|
||||
title: Use React DOM Resource Hints
|
||||
impact: HIGH
|
||||
impactDescription: reduces load time for critical resources
|
||||
tags: rendering, preload, preconnect, prefetch, resource-hints
|
||||
---
|
||||
|
||||
## Use React DOM Resource Hints
|
||||
|
||||
**Impact: HIGH (reduces load time for critical resources)**
|
||||
|
||||
React DOM provides APIs to hint the browser about resources it will need. These are especially useful in server components to start loading resources before the client even receives the HTML.
|
||||
|
||||
- **`prefetchDNS(href)`**: Resolve DNS for a domain you expect to connect to
|
||||
- **`preconnect(href)`**: Establish connection (DNS + TCP + TLS) to a server
|
||||
- **`preload(href, options)`**: Fetch a resource (stylesheet, font, script, image) you'll use soon
|
||||
- **`preloadModule(href)`**: Fetch an ES module you'll use soon
|
||||
- **`preinit(href, options)`**: Fetch and evaluate a stylesheet or script
|
||||
- **`preinitModule(href)`**: Fetch and evaluate an ES module
|
||||
|
||||
**Example (preconnect to third-party APIs):**
|
||||
|
||||
```tsx
|
||||
import { preconnect, prefetchDNS } from 'react-dom'
|
||||
|
||||
export default function App() {
|
||||
prefetchDNS('https://analytics.example.com')
|
||||
preconnect('https://api.example.com')
|
||||
|
||||
return <main>{/* content */}</main>
|
||||
}
|
||||
```
|
||||
|
||||
**Example (preload critical fonts and styles):**
|
||||
|
||||
```tsx
|
||||
import { preload, preinit } from 'react-dom'
|
||||
|
||||
export default function RootLayout({ children }) {
|
||||
// Preload font file
|
||||
preload('/fonts/inter.woff2', { as: 'font', type: 'font/woff2', crossOrigin: 'anonymous' })
|
||||
|
||||
// Fetch and apply critical stylesheet immediately
|
||||
preinit('/styles/critical.css', { as: 'style' })
|
||||
|
||||
return (
|
||||
<html>
|
||||
<body>{children}</body>
|
||||
</html>
|
||||
)
|
||||
}
|
||||
```
|
||||
|
||||
**Example (preload modules for code-split routes):**
|
||||
|
||||
```tsx
|
||||
import { preloadModule, preinitModule } from 'react-dom'
|
||||
|
||||
function Navigation() {
|
||||
const preloadDashboard = () => {
|
||||
preloadModule('/dashboard.js', { as: 'script' })
|
||||
}
|
||||
|
||||
return (
|
||||
<nav>
|
||||
<a href="/dashboard" onMouseEnter={preloadDashboard}>
|
||||
Dashboard
|
||||
</a>
|
||||
</nav>
|
||||
)
|
||||
}
|
||||
```
|
||||
|
||||
**When to use each:**
|
||||
|
||||
| API | Use case |
|
||||
|-----|----------|
|
||||
| `prefetchDNS` | Third-party domains you'll connect to later |
|
||||
| `preconnect` | APIs or CDNs you'll fetch from immediately |
|
||||
| `preload` | Critical resources needed for current page |
|
||||
| `preloadModule` | JS modules for likely next navigation |
|
||||
| `preinit` | Stylesheets/scripts that must execute early |
|
||||
| `preinitModule` | ES modules that must execute early |
|
||||
|
||||
Reference: [React DOM Resource Preloading APIs](https://react.dev/reference/react-dom#resource-preloading-apis)
|
||||
@@ -1,68 +0,0 @@
|
||||
---
|
||||
title: Use defer or async on Script Tags
|
||||
impact: HIGH
|
||||
impactDescription: eliminates render-blocking
|
||||
tags: rendering, script, defer, async, performance
|
||||
---
|
||||
|
||||
## Use defer or async on Script Tags
|
||||
|
||||
**Impact: HIGH (eliminates render-blocking)**
|
||||
|
||||
Script tags without `defer` or `async` block HTML parsing while the script downloads and executes. This delays First Contentful Paint and Time to Interactive.
|
||||
|
||||
- **`defer`**: Downloads in parallel, executes after HTML parsing completes, maintains execution order
|
||||
- **`async`**: Downloads in parallel, executes immediately when ready, no guaranteed order
|
||||
|
||||
Use `defer` for scripts that depend on DOM or other scripts. Use `async` for independent scripts like analytics.
|
||||
|
||||
**Incorrect (blocks rendering):**
|
||||
|
||||
```tsx
|
||||
export default function Document() {
|
||||
return (
|
||||
<html>
|
||||
<head>
|
||||
<script src="https://example.com/analytics.js" />
|
||||
<script src="/scripts/utils.js" />
|
||||
</head>
|
||||
<body>{/* content */}</body>
|
||||
</html>
|
||||
)
|
||||
}
|
||||
```
|
||||
|
||||
**Correct (non-blocking):**
|
||||
|
||||
```tsx
|
||||
export default function Document() {
|
||||
return (
|
||||
<html>
|
||||
<head>
|
||||
{/* Independent script - use async */}
|
||||
<script src="https://example.com/analytics.js" async />
|
||||
{/* DOM-dependent script - use defer */}
|
||||
<script src="/scripts/utils.js" defer />
|
||||
</head>
|
||||
<body>{/* content */}</body>
|
||||
</html>
|
||||
)
|
||||
}
|
||||
```
|
||||
|
||||
**Note:** In Next.js, prefer the `next/script` component with `strategy` prop instead of raw script tags:
|
||||
|
||||
```tsx
|
||||
import Script from 'next/script'
|
||||
|
||||
export default function Page() {
|
||||
return (
|
||||
<>
|
||||
<Script src="https://example.com/analytics.js" strategy="afterInteractive" />
|
||||
<Script src="/scripts/utils.js" strategy="beforeInteractive" />
|
||||
</>
|
||||
)
|
||||
}
|
||||
```
|
||||
|
||||
Reference: [MDN - Script element](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/script#defer)
|
||||
@@ -1,28 +0,0 @@
|
||||
---
|
||||
title: Optimize SVG Precision
|
||||
impact: LOW
|
||||
impactDescription: reduces file size
|
||||
tags: rendering, svg, optimization, svgo
|
||||
---
|
||||
|
||||
## Optimize SVG Precision
|
||||
|
||||
Reduce SVG coordinate precision to decrease file size. The optimal precision depends on the viewBox size, but in general reducing precision should be considered.
|
||||
|
||||
**Incorrect (excessive precision):**
|
||||
|
||||
```svg
|
||||
<path d="M 10.293847 20.847362 L 30.938472 40.192837" />
|
||||
```
|
||||
|
||||
**Correct (1 decimal place):**
|
||||
|
||||
```svg
|
||||
<path d="M 10.3 20.8 L 30.9 40.2" />
|
||||
```
|
||||
|
||||
**Automate with SVGO:**
|
||||
|
||||
```bash
|
||||
npx svgo --precision=1 --multipass icon.svg
|
||||
```
|
||||
-75
@@ -1,75 +0,0 @@
|
||||
---
|
||||
title: Use useTransition Over Manual Loading States
|
||||
impact: LOW
|
||||
impactDescription: reduces re-renders and improves code clarity
|
||||
tags: rendering, transitions, useTransition, loading, state
|
||||
---
|
||||
|
||||
## Use useTransition Over Manual Loading States
|
||||
|
||||
Use `useTransition` instead of manual `useState` for loading states. This provides built-in `isPending` state and automatically manages transitions.
|
||||
|
||||
**Incorrect (manual loading state):**
|
||||
|
||||
```tsx
|
||||
function SearchResults() {
|
||||
const [query, setQuery] = useState('')
|
||||
const [results, setResults] = useState([])
|
||||
const [isLoading, setIsLoading] = useState(false)
|
||||
|
||||
const handleSearch = async (value: string) => {
|
||||
setIsLoading(true)
|
||||
setQuery(value)
|
||||
const data = await fetchResults(value)
|
||||
setResults(data)
|
||||
setIsLoading(false)
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<input onChange={(e) => handleSearch(e.target.value)} />
|
||||
{isLoading && <Spinner />}
|
||||
<ResultsList results={results} />
|
||||
</>
|
||||
)
|
||||
}
|
||||
```
|
||||
|
||||
**Correct (useTransition with built-in pending state):**
|
||||
|
||||
```tsx
|
||||
import { useTransition, useState } from 'react'
|
||||
|
||||
function SearchResults() {
|
||||
const [query, setQuery] = useState('')
|
||||
const [results, setResults] = useState([])
|
||||
const [isPending, startTransition] = useTransition()
|
||||
|
||||
const handleSearch = (value: string) => {
|
||||
setQuery(value) // Update input immediately
|
||||
|
||||
startTransition(async () => {
|
||||
// Fetch and update results
|
||||
const data = await fetchResults(value)
|
||||
setResults(data)
|
||||
})
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<input onChange={(e) => handleSearch(e.target.value)} />
|
||||
{isPending && <Spinner />}
|
||||
<ResultsList results={results} />
|
||||
</>
|
||||
)
|
||||
}
|
||||
```
|
||||
|
||||
**Benefits:**
|
||||
|
||||
- **Automatic pending state**: No need to manually manage `setIsLoading(true/false)`
|
||||
- **Error resilience**: Pending state correctly resets even if the transition throws
|
||||
- **Better responsiveness**: Keeps the UI responsive during updates
|
||||
- **Interrupt handling**: New transitions automatically cancel pending ones
|
||||
|
||||
Reference: [useTransition](https://react.dev/reference/react/useTransition)
|
||||
@@ -1,39 +0,0 @@
|
||||
---
|
||||
title: Defer State Reads to Usage Point
|
||||
impact: MEDIUM
|
||||
impactDescription: avoids unnecessary subscriptions
|
||||
tags: rerender, searchParams, localStorage, optimization
|
||||
---
|
||||
|
||||
## Defer State Reads to Usage Point
|
||||
|
||||
Don't subscribe to dynamic state (searchParams, localStorage) if you only read it inside callbacks.
|
||||
|
||||
**Incorrect (subscribes to all searchParams changes):**
|
||||
|
||||
```tsx
|
||||
function ShareButton({ chatId }: { chatId: string }) {
|
||||
const searchParams = useSearchParams()
|
||||
|
||||
const handleShare = () => {
|
||||
const ref = searchParams.get('ref')
|
||||
shareChat(chatId, { ref })
|
||||
}
|
||||
|
||||
return <button onClick={handleShare}>Share</button>
|
||||
}
|
||||
```
|
||||
|
||||
**Correct (reads on demand, no subscription):**
|
||||
|
||||
```tsx
|
||||
function ShareButton({ chatId }: { chatId: string }) {
|
||||
const handleShare = () => {
|
||||
const params = new URLSearchParams(window.location.search)
|
||||
const ref = params.get('ref')
|
||||
shareChat(chatId, { ref })
|
||||
}
|
||||
|
||||
return <button onClick={handleShare}>Share</button>
|
||||
}
|
||||
```
|
||||
@@ -1,45 +0,0 @@
|
||||
---
|
||||
title: Narrow Effect Dependencies
|
||||
impact: LOW
|
||||
impactDescription: minimizes effect re-runs
|
||||
tags: rerender, useEffect, dependencies, optimization
|
||||
---
|
||||
|
||||
## Narrow Effect Dependencies
|
||||
|
||||
Specify primitive dependencies instead of objects to minimize effect re-runs.
|
||||
|
||||
**Incorrect (re-runs on any user field change):**
|
||||
|
||||
```tsx
|
||||
useEffect(() => {
|
||||
console.log(user.id)
|
||||
}, [user])
|
||||
```
|
||||
|
||||
**Correct (re-runs only when id changes):**
|
||||
|
||||
```tsx
|
||||
useEffect(() => {
|
||||
console.log(user.id)
|
||||
}, [user.id])
|
||||
```
|
||||
|
||||
**For derived state, compute outside effect:**
|
||||
|
||||
```tsx
|
||||
// Incorrect: runs on width=767, 766, 765...
|
||||
useEffect(() => {
|
||||
if (width < 768) {
|
||||
enableMobileMode()
|
||||
}
|
||||
}, [width])
|
||||
|
||||
// Correct: runs only on boolean transition
|
||||
const isMobile = width < 768
|
||||
useEffect(() => {
|
||||
if (isMobile) {
|
||||
enableMobileMode()
|
||||
}
|
||||
}, [isMobile])
|
||||
```
|
||||
-40
@@ -1,40 +0,0 @@
|
||||
---
|
||||
title: Calculate Derived State During Rendering
|
||||
impact: MEDIUM
|
||||
impactDescription: avoids redundant renders and state drift
|
||||
tags: rerender, derived-state, useEffect, state
|
||||
---
|
||||
|
||||
## Calculate Derived State During Rendering
|
||||
|
||||
If a value can be computed from current props/state, do not store it in state or update it in an effect. Derive it during render to avoid extra renders and state drift. Do not set state in effects solely in response to prop changes; prefer derived values or keyed resets instead.
|
||||
|
||||
**Incorrect (redundant state and effect):**
|
||||
|
||||
```tsx
|
||||
function Form() {
|
||||
const [firstName, setFirstName] = useState('First')
|
||||
const [lastName, setLastName] = useState('Last')
|
||||
const [fullName, setFullName] = useState('')
|
||||
|
||||
useEffect(() => {
|
||||
setFullName(firstName + ' ' + lastName)
|
||||
}, [firstName, lastName])
|
||||
|
||||
return <p>{fullName}</p>
|
||||
}
|
||||
```
|
||||
|
||||
**Correct (derive during render):**
|
||||
|
||||
```tsx
|
||||
function Form() {
|
||||
const [firstName, setFirstName] = useState('First')
|
||||
const [lastName, setLastName] = useState('Last')
|
||||
const fullName = firstName + ' ' + lastName
|
||||
|
||||
return <p>{fullName}</p>
|
||||
}
|
||||
```
|
||||
|
||||
References: [You Might Not Need an Effect](https://react.dev/learn/you-might-not-need-an-effect)
|
||||
@@ -1,29 +0,0 @@
|
||||
---
|
||||
title: Subscribe to Derived State
|
||||
impact: MEDIUM
|
||||
impactDescription: reduces re-render frequency
|
||||
tags: rerender, derived-state, media-query, optimization
|
||||
---
|
||||
|
||||
## Subscribe to Derived State
|
||||
|
||||
Subscribe to derived boolean state instead of continuous values to reduce re-render frequency.
|
||||
|
||||
**Incorrect (re-renders on every pixel change):**
|
||||
|
||||
```tsx
|
||||
function Sidebar() {
|
||||
const width = useWindowWidth() // updates continuously
|
||||
const isMobile = width < 768
|
||||
return <nav className={isMobile ? 'mobile' : 'desktop'} />
|
||||
}
|
||||
```
|
||||
|
||||
**Correct (re-renders only when boolean changes):**
|
||||
|
||||
```tsx
|
||||
function Sidebar() {
|
||||
const isMobile = useMediaQuery('(max-width: 767px)')
|
||||
return <nav className={isMobile ? 'mobile' : 'desktop'} />
|
||||
}
|
||||
```
|
||||
@@ -1,74 +0,0 @@
|
||||
---
|
||||
title: Use Functional setState Updates
|
||||
impact: MEDIUM
|
||||
impactDescription: prevents stale closures and unnecessary callback recreations
|
||||
tags: react, hooks, useState, useCallback, callbacks, closures
|
||||
---
|
||||
|
||||
## Use Functional setState Updates
|
||||
|
||||
When updating state based on the current state value, use the functional update form of setState instead of directly referencing the state variable. This prevents stale closures, eliminates unnecessary dependencies, and creates stable callback references.
|
||||
|
||||
**Incorrect (requires state as dependency):**
|
||||
|
||||
```tsx
|
||||
function TodoList() {
|
||||
const [items, setItems] = useState(initialItems)
|
||||
|
||||
// Callback must depend on items, recreated on every items change
|
||||
const addItems = useCallback((newItems: Item[]) => {
|
||||
setItems([...items, ...newItems])
|
||||
}, [items]) // ❌ items dependency causes recreations
|
||||
|
||||
// Risk of stale closure if dependency is forgotten
|
||||
const removeItem = useCallback((id: string) => {
|
||||
setItems(items.filter(item => item.id !== id))
|
||||
}, []) // ❌ Missing items dependency - will use stale items!
|
||||
|
||||
return <ItemsEditor items={items} onAdd={addItems} onRemove={removeItem} />
|
||||
}
|
||||
```
|
||||
|
||||
The first callback is recreated every time `items` changes, which can cause child components to re-render unnecessarily. The second callback has a stale closure bug—it will always reference the initial `items` value.
|
||||
|
||||
**Correct (stable callbacks, no stale closures):**
|
||||
|
||||
```tsx
|
||||
function TodoList() {
|
||||
const [items, setItems] = useState(initialItems)
|
||||
|
||||
// Stable callback, never recreated
|
||||
const addItems = useCallback((newItems: Item[]) => {
|
||||
setItems(curr => [...curr, ...newItems])
|
||||
}, []) // ✅ No dependencies needed
|
||||
|
||||
// Always uses latest state, no stale closure risk
|
||||
const removeItem = useCallback((id: string) => {
|
||||
setItems(curr => curr.filter(item => item.id !== id))
|
||||
}, []) // ✅ Safe and stable
|
||||
|
||||
return <ItemsEditor items={items} onAdd={addItems} onRemove={removeItem} />
|
||||
}
|
||||
```
|
||||
|
||||
**Benefits:**
|
||||
|
||||
1. **Stable callback references** - Callbacks don't need to be recreated when state changes
|
||||
2. **No stale closures** - Always operates on the latest state value
|
||||
3. **Fewer dependencies** - Simplifies dependency arrays and reduces memory leaks
|
||||
4. **Prevents bugs** - Eliminates the most common source of React closure bugs
|
||||
|
||||
**When to use functional updates:**
|
||||
|
||||
- Any setState that depends on the current state value
|
||||
- Inside useCallback/useMemo when state is needed
|
||||
- Event handlers that reference state
|
||||
- Async operations that update state
|
||||
|
||||
**When direct updates are fine:**
|
||||
|
||||
- Setting state to a static value: `setCount(0)`
|
||||
- Setting state from props/arguments only: `setName(newName)`
|
||||
- State doesn't depend on previous value
|
||||
|
||||
**Note:** If your project has [React Compiler](https://react.dev/learn/react-compiler) enabled, the compiler can automatically optimize some cases, but functional updates are still recommended for correctness and to prevent stale closure bugs.
|
||||
@@ -1,58 +0,0 @@
|
||||
---
|
||||
title: Use Lazy State Initialization
|
||||
impact: MEDIUM
|
||||
impactDescription: wasted computation on every render
|
||||
tags: react, hooks, useState, performance, initialization
|
||||
---
|
||||
|
||||
## Use Lazy State Initialization
|
||||
|
||||
Pass a function to `useState` for expensive initial values. Without the function form, the initializer runs on every render even though the value is only used once.
|
||||
|
||||
**Incorrect (runs on every render):**
|
||||
|
||||
```tsx
|
||||
function FilteredList({ items }: { items: Item[] }) {
|
||||
// buildSearchIndex() runs on EVERY render, even after initialization
|
||||
const [searchIndex, setSearchIndex] = useState(buildSearchIndex(items))
|
||||
const [query, setQuery] = useState('')
|
||||
|
||||
// When query changes, buildSearchIndex runs again unnecessarily
|
||||
return <SearchResults index={searchIndex} query={query} />
|
||||
}
|
||||
|
||||
function UserProfile() {
|
||||
// JSON.parse runs on every render
|
||||
const [settings, setSettings] = useState(
|
||||
JSON.parse(localStorage.getItem('settings') || '{}')
|
||||
)
|
||||
|
||||
return <SettingsForm settings={settings} onChange={setSettings} />
|
||||
}
|
||||
```
|
||||
|
||||
**Correct (runs only once):**
|
||||
|
||||
```tsx
|
||||
function FilteredList({ items }: { items: Item[] }) {
|
||||
// buildSearchIndex() runs ONLY on initial render
|
||||
const [searchIndex, setSearchIndex] = useState(() => buildSearchIndex(items))
|
||||
const [query, setQuery] = useState('')
|
||||
|
||||
return <SearchResults index={searchIndex} query={query} />
|
||||
}
|
||||
|
||||
function UserProfile() {
|
||||
// JSON.parse runs only on initial render
|
||||
const [settings, setSettings] = useState(() => {
|
||||
const stored = localStorage.getItem('settings')
|
||||
return stored ? JSON.parse(stored) : {}
|
||||
})
|
||||
|
||||
return <SettingsForm settings={settings} onChange={setSettings} />
|
||||
}
|
||||
```
|
||||
|
||||
Use lazy initialization when computing initial values from localStorage/sessionStorage, building data structures (indexes, maps), reading from the DOM, or performing heavy transformations.
|
||||
|
||||
For simple primitives (`useState(0)`), direct references (`useState(props.value)`), or cheap literals (`useState({})`), the function form is unnecessary.
|
||||
-38
@@ -1,38 +0,0 @@
|
||||
---
|
||||
|
||||
title: Extract Default Non-primitive Parameter Value from Memoized Component to Constant
|
||||
impact: MEDIUM
|
||||
impactDescription: restores memoization by using a constant for default value
|
||||
tags: rerender, memo, optimization
|
||||
|
||||
---
|
||||
|
||||
## Extract Default Non-primitive Parameter Value from Memoized Component to Constant
|
||||
|
||||
When memoized component has a default value for some non-primitive optional parameter, such as an array, function, or object, calling the component without that parameter results in broken memoization. This is because new value instances are created on every rerender, and they do not pass strict equality comparison in `memo()`.
|
||||
|
||||
To address this issue, extract the default value into a constant.
|
||||
|
||||
**Incorrect (`onClick` has different values on every rerender):**
|
||||
|
||||
```tsx
|
||||
const UserAvatar = memo(function UserAvatar({ onClick = () => {} }: { onClick?: () => void }) {
|
||||
// ...
|
||||
})
|
||||
|
||||
// Used without optional onClick
|
||||
<UserAvatar />
|
||||
```
|
||||
|
||||
**Correct (stable default value):**
|
||||
|
||||
```tsx
|
||||
const NOOP = () => {};
|
||||
|
||||
const UserAvatar = memo(function UserAvatar({ onClick = NOOP }: { onClick?: () => void }) {
|
||||
// ...
|
||||
})
|
||||
|
||||
// Used without optional onClick
|
||||
<UserAvatar />
|
||||
```
|
||||
@@ -1,44 +0,0 @@
|
||||
---
|
||||
title: Extract to Memoized Components
|
||||
impact: MEDIUM
|
||||
impactDescription: enables early returns
|
||||
tags: rerender, memo, useMemo, optimization
|
||||
---
|
||||
|
||||
## Extract to Memoized Components
|
||||
|
||||
Extract expensive work into memoized components to enable early returns before computation.
|
||||
|
||||
**Incorrect (computes avatar even when loading):**
|
||||
|
||||
```tsx
|
||||
function Profile({ user, loading }: Props) {
|
||||
const avatar = useMemo(() => {
|
||||
const id = computeAvatarId(user)
|
||||
return <Avatar id={id} />
|
||||
}, [user])
|
||||
|
||||
if (loading) return <Skeleton />
|
||||
return <div>{avatar}</div>
|
||||
}
|
||||
```
|
||||
|
||||
**Correct (skips computation when loading):**
|
||||
|
||||
```tsx
|
||||
const UserAvatar = memo(function UserAvatar({ user }: { user: User }) {
|
||||
const id = useMemo(() => computeAvatarId(user), [user])
|
||||
return <Avatar id={id} />
|
||||
})
|
||||
|
||||
function Profile({ user, loading }: Props) {
|
||||
if (loading) return <Skeleton />
|
||||
return (
|
||||
<div>
|
||||
<UserAvatar user={user} />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
```
|
||||
|
||||
**Note:** If your project has [React Compiler](https://react.dev/learn/react-compiler) enabled, manual memoization with `memo()` and `useMemo()` is not necessary. The compiler automatically optimizes re-renders.
|
||||
@@ -1,45 +0,0 @@
|
||||
---
|
||||
title: Put Interaction Logic in Event Handlers
|
||||
impact: MEDIUM
|
||||
impactDescription: avoids effect re-runs and duplicate side effects
|
||||
tags: rerender, useEffect, events, side-effects, dependencies
|
||||
---
|
||||
|
||||
## Put Interaction Logic in Event Handlers
|
||||
|
||||
If a side effect is triggered by a specific user action (submit, click, drag), run it in that event handler. Do not model the action as state + effect; it makes effects re-run on unrelated changes and can duplicate the action.
|
||||
|
||||
**Incorrect (event modeled as state + effect):**
|
||||
|
||||
```tsx
|
||||
function Form() {
|
||||
const [submitted, setSubmitted] = useState(false)
|
||||
const theme = useContext(ThemeContext)
|
||||
|
||||
useEffect(() => {
|
||||
if (submitted) {
|
||||
post('/api/register')
|
||||
showToast('Registered', theme)
|
||||
}
|
||||
}, [submitted, theme])
|
||||
|
||||
return <button onClick={() => setSubmitted(true)}>Submit</button>
|
||||
}
|
||||
```
|
||||
|
||||
**Correct (do it in the handler):**
|
||||
|
||||
```tsx
|
||||
function Form() {
|
||||
const theme = useContext(ThemeContext)
|
||||
|
||||
function handleSubmit() {
|
||||
post('/api/register')
|
||||
showToast('Registered', theme)
|
||||
}
|
||||
|
||||
return <button onClick={handleSubmit}>Submit</button>
|
||||
}
|
||||
```
|
||||
|
||||
Reference: [Should this code move to an event handler?](https://react.dev/learn/removing-effect-dependencies#should-this-code-move-to-an-event-handler)
|
||||
@@ -1,82 +0,0 @@
|
||||
---
|
||||
title: Don't Define Components Inside Components
|
||||
impact: HIGH
|
||||
impactDescription: prevents remount on every render
|
||||
tags: rerender, components, remount, performance
|
||||
---
|
||||
|
||||
## Don't Define Components Inside Components
|
||||
|
||||
**Impact: HIGH (prevents remount on every render)**
|
||||
|
||||
Defining a component inside another component creates a new component type on every render. React sees a different component each time and fully remounts it, destroying all state and DOM.
|
||||
|
||||
A common reason developers do this is to access parent variables without passing props. Always pass props instead.
|
||||
|
||||
**Incorrect (remounts on every render):**
|
||||
|
||||
```tsx
|
||||
function UserProfile({ user, theme }) {
|
||||
// Defined inside to access `theme` - BAD
|
||||
const Avatar = () => (
|
||||
<img
|
||||
src={user.avatarUrl}
|
||||
className={theme === 'dark' ? 'avatar-dark' : 'avatar-light'}
|
||||
/>
|
||||
)
|
||||
|
||||
// Defined inside to access `user` - BAD
|
||||
const Stats = () => (
|
||||
<div>
|
||||
<span>{user.followers} followers</span>
|
||||
<span>{user.posts} posts</span>
|
||||
</div>
|
||||
)
|
||||
|
||||
return (
|
||||
<div>
|
||||
<Avatar />
|
||||
<Stats />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
```
|
||||
|
||||
Every time `UserProfile` renders, `Avatar` and `Stats` are new component types. React unmounts the old instances and mounts new ones, losing any internal state, running effects again, and recreating DOM nodes.
|
||||
|
||||
**Correct (pass props instead):**
|
||||
|
||||
```tsx
|
||||
function Avatar({ src, theme }: { src: string; theme: string }) {
|
||||
return (
|
||||
<img
|
||||
src={src}
|
||||
className={theme === 'dark' ? 'avatar-dark' : 'avatar-light'}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function Stats({ followers, posts }: { followers: number; posts: number }) {
|
||||
return (
|
||||
<div>
|
||||
<span>{followers} followers</span>
|
||||
<span>{posts} posts</span>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function UserProfile({ user, theme }) {
|
||||
return (
|
||||
<div>
|
||||
<Avatar src={user.avatarUrl} theme={theme} />
|
||||
<Stats followers={user.followers} posts={user.posts} />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
```
|
||||
|
||||
**Symptoms of this bug:**
|
||||
- Input fields lose focus on every keystroke
|
||||
- Animations restart unexpectedly
|
||||
- `useEffect` cleanup/setup runs on every parent render
|
||||
- Scroll position resets inside the component
|
||||
-35
@@ -1,35 +0,0 @@
|
||||
---
|
||||
title: Do not wrap a simple expression with a primitive result type in useMemo
|
||||
impact: LOW-MEDIUM
|
||||
impactDescription: wasted computation on every render
|
||||
tags: rerender, useMemo, optimization
|
||||
---
|
||||
|
||||
## Do not wrap a simple expression with a primitive result type in useMemo
|
||||
|
||||
When an expression is simple (few logical or arithmetical operators) and has a primitive result type (boolean, number, string), do not wrap it in `useMemo`.
|
||||
Calling `useMemo` and comparing hook dependencies may consume more resources than the expression itself.
|
||||
|
||||
**Incorrect:**
|
||||
|
||||
```tsx
|
||||
function Header({ user, notifications }: Props) {
|
||||
const isLoading = useMemo(() => {
|
||||
return user.isLoading || notifications.isLoading
|
||||
}, [user.isLoading, notifications.isLoading])
|
||||
|
||||
if (isLoading) return <Skeleton />
|
||||
// return some markup
|
||||
}
|
||||
```
|
||||
|
||||
**Correct:**
|
||||
|
||||
```tsx
|
||||
function Header({ user, notifications }: Props) {
|
||||
const isLoading = user.isLoading || notifications.isLoading
|
||||
|
||||
if (isLoading) return <Skeleton />
|
||||
// return some markup
|
||||
}
|
||||
```
|
||||
@@ -1,64 +0,0 @@
|
||||
---
|
||||
title: Split Combined Hook Computations
|
||||
impact: MEDIUM
|
||||
impactDescription: avoids recomputing independent steps
|
||||
tags: rerender, useMemo, useEffect, dependencies, optimization
|
||||
---
|
||||
|
||||
## Split Combined Hook Computations
|
||||
|
||||
When a hook contains multiple independent tasks with different dependencies, split them into separate hooks. A combined hook reruns all tasks when any dependency changes, even if some tasks don't use the changed value.
|
||||
|
||||
**Incorrect (changing `sortOrder` recomputes filtering):**
|
||||
|
||||
```tsx
|
||||
const sortedProducts = useMemo(() => {
|
||||
const filtered = products.filter((p) => p.category === category)
|
||||
const sorted = filtered.toSorted((a, b) =>
|
||||
sortOrder === "asc" ? a.price - b.price : b.price - a.price
|
||||
)
|
||||
return sorted
|
||||
}, [products, category, sortOrder])
|
||||
```
|
||||
|
||||
**Correct (filtering only recomputes when products or category change):**
|
||||
|
||||
```tsx
|
||||
const filteredProducts = useMemo(
|
||||
() => products.filter((p) => p.category === category),
|
||||
[products, category]
|
||||
)
|
||||
|
||||
const sortedProducts = useMemo(
|
||||
() =>
|
||||
filteredProducts.toSorted((a, b) =>
|
||||
sortOrder === "asc" ? a.price - b.price : b.price - a.price
|
||||
),
|
||||
[filteredProducts, sortOrder]
|
||||
)
|
||||
```
|
||||
|
||||
This pattern also applies to `useEffect` when combining unrelated side effects:
|
||||
|
||||
**Incorrect (both effects run when either dependency changes):**
|
||||
|
||||
```tsx
|
||||
useEffect(() => {
|
||||
analytics.trackPageView(pathname)
|
||||
document.title = `${pageTitle} | My App`
|
||||
}, [pathname, pageTitle])
|
||||
```
|
||||
|
||||
**Correct (effects run independently):**
|
||||
|
||||
```tsx
|
||||
useEffect(() => {
|
||||
analytics.trackPageView(pathname)
|
||||
}, [pathname])
|
||||
|
||||
useEffect(() => {
|
||||
document.title = `${pageTitle} | My App`
|
||||
}, [pageTitle])
|
||||
```
|
||||
|
||||
**Note:** If your project has [React Compiler](https://react.dev/learn/react-compiler) enabled, it automatically optimizes dependency tracking and may handle some of these cases for you.
|
||||
@@ -1,40 +0,0 @@
|
||||
---
|
||||
title: Use Transitions for Non-Urgent Updates
|
||||
impact: MEDIUM
|
||||
impactDescription: maintains UI responsiveness
|
||||
tags: rerender, transitions, startTransition, performance
|
||||
---
|
||||
|
||||
## Use Transitions for Non-Urgent Updates
|
||||
|
||||
Mark frequent, non-urgent state updates as transitions to maintain UI responsiveness.
|
||||
|
||||
**Incorrect (blocks UI on every scroll):**
|
||||
|
||||
```tsx
|
||||
function ScrollTracker() {
|
||||
const [scrollY, setScrollY] = useState(0)
|
||||
useEffect(() => {
|
||||
const handler = () => setScrollY(window.scrollY)
|
||||
window.addEventListener('scroll', handler, { passive: true })
|
||||
return () => window.removeEventListener('scroll', handler)
|
||||
}, [])
|
||||
}
|
||||
```
|
||||
|
||||
**Correct (non-blocking updates):**
|
||||
|
||||
```tsx
|
||||
import { startTransition } from 'react'
|
||||
|
||||
function ScrollTracker() {
|
||||
const [scrollY, setScrollY] = useState(0)
|
||||
useEffect(() => {
|
||||
const handler = () => {
|
||||
startTransition(() => setScrollY(window.scrollY))
|
||||
}
|
||||
window.addEventListener('scroll', handler, { passive: true })
|
||||
return () => window.removeEventListener('scroll', handler)
|
||||
}, [])
|
||||
}
|
||||
```
|
||||
@@ -1,59 +0,0 @@
|
||||
---
|
||||
title: Use useDeferredValue for Expensive Derived Renders
|
||||
impact: MEDIUM
|
||||
impactDescription: keeps input responsive during heavy computation
|
||||
tags: rerender, useDeferredValue, optimization, concurrent
|
||||
---
|
||||
|
||||
## Use useDeferredValue for Expensive Derived Renders
|
||||
|
||||
When user input triggers expensive computations or renders, use `useDeferredValue` to keep the input responsive. The deferred value lags behind, allowing React to prioritize the input update and render the expensive result when idle.
|
||||
|
||||
**Incorrect (input feels laggy while filtering):**
|
||||
|
||||
```tsx
|
||||
function Search({ items }: { items: Item[] }) {
|
||||
const [query, setQuery] = useState('')
|
||||
const filtered = items.filter(item => fuzzyMatch(item, query))
|
||||
|
||||
return (
|
||||
<>
|
||||
<input value={query} onChange={e => setQuery(e.target.value)} />
|
||||
<ResultsList results={filtered} />
|
||||
</>
|
||||
)
|
||||
}
|
||||
```
|
||||
|
||||
**Correct (input stays snappy, results render when ready):**
|
||||
|
||||
```tsx
|
||||
function Search({ items }: { items: Item[] }) {
|
||||
const [query, setQuery] = useState('')
|
||||
const deferredQuery = useDeferredValue(query)
|
||||
const filtered = useMemo(
|
||||
() => items.filter(item => fuzzyMatch(item, deferredQuery)),
|
||||
[items, deferredQuery]
|
||||
)
|
||||
const isStale = query !== deferredQuery
|
||||
|
||||
return (
|
||||
<>
|
||||
<input value={query} onChange={e => setQuery(e.target.value)} />
|
||||
<div style={{ opacity: isStale ? 0.7 : 1 }}>
|
||||
<ResultsList results={filtered} />
|
||||
</div>
|
||||
</>
|
||||
)
|
||||
}
|
||||
```
|
||||
|
||||
**When to use:**
|
||||
|
||||
- Filtering/searching large lists
|
||||
- Expensive visualizations (charts, graphs) reacting to input
|
||||
- Any derived state that causes noticeable render delays
|
||||
|
||||
**Note:** Wrap the expensive computation in `useMemo` with the deferred value as a dependency, otherwise it still runs on every render.
|
||||
|
||||
Reference: [React useDeferredValue](https://react.dev/reference/react/useDeferredValue)
|
||||
-73
@@ -1,73 +0,0 @@
|
||||
---
|
||||
title: Use useRef for Transient Values
|
||||
impact: MEDIUM
|
||||
impactDescription: avoids unnecessary re-renders on frequent updates
|
||||
tags: rerender, useref, state, performance
|
||||
---
|
||||
|
||||
## Use useRef for Transient Values
|
||||
|
||||
When a value changes frequently and you don't want a re-render on every update (e.g., mouse trackers, intervals, transient flags), store it in `useRef` instead of `useState`. Keep component state for UI; use refs for temporary DOM-adjacent values. Updating a ref does not trigger a re-render.
|
||||
|
||||
**Incorrect (renders every update):**
|
||||
|
||||
```tsx
|
||||
function Tracker() {
|
||||
const [lastX, setLastX] = useState(0)
|
||||
|
||||
useEffect(() => {
|
||||
const onMove = (e: MouseEvent) => setLastX(e.clientX)
|
||||
window.addEventListener('mousemove', onMove)
|
||||
return () => window.removeEventListener('mousemove', onMove)
|
||||
}, [])
|
||||
|
||||
return (
|
||||
<div
|
||||
style={{
|
||||
position: 'fixed',
|
||||
top: 0,
|
||||
left: lastX,
|
||||
width: 8,
|
||||
height: 8,
|
||||
background: 'black',
|
||||
}}
|
||||
/>
|
||||
)
|
||||
}
|
||||
```
|
||||
|
||||
**Correct (no re-render for tracking):**
|
||||
|
||||
```tsx
|
||||
function Tracker() {
|
||||
const lastXRef = useRef(0)
|
||||
const dotRef = useRef<HTMLDivElement>(null)
|
||||
|
||||
useEffect(() => {
|
||||
const onMove = (e: MouseEvent) => {
|
||||
lastXRef.current = e.clientX
|
||||
const node = dotRef.current
|
||||
if (node) {
|
||||
node.style.transform = `translateX(${e.clientX}px)`
|
||||
}
|
||||
}
|
||||
window.addEventListener('mousemove', onMove)
|
||||
return () => window.removeEventListener('mousemove', onMove)
|
||||
}, [])
|
||||
|
||||
return (
|
||||
<div
|
||||
ref={dotRef}
|
||||
style={{
|
||||
position: 'fixed',
|
||||
top: 0,
|
||||
left: 0,
|
||||
width: 8,
|
||||
height: 8,
|
||||
background: 'black',
|
||||
transform: 'translateX(0px)',
|
||||
}}
|
||||
/>
|
||||
)
|
||||
}
|
||||
```
|
||||
@@ -1,73 +0,0 @@
|
||||
---
|
||||
title: Use after() for Non-Blocking Operations
|
||||
impact: MEDIUM
|
||||
impactDescription: faster response times
|
||||
tags: server, async, logging, analytics, side-effects
|
||||
---
|
||||
|
||||
## Use after() for Non-Blocking Operations
|
||||
|
||||
Use Next.js's `after()` to schedule work that should execute after a response is sent. This prevents logging, analytics, and other side effects from blocking the response.
|
||||
|
||||
**Incorrect (blocks response):**
|
||||
|
||||
```tsx
|
||||
import { logUserAction } from '@/app/utils'
|
||||
|
||||
export async function POST(request: Request) {
|
||||
// Perform mutation
|
||||
await updateDatabase(request)
|
||||
|
||||
// Logging blocks the response
|
||||
const userAgent = request.headers.get('user-agent') || 'unknown'
|
||||
await logUserAction({ userAgent })
|
||||
|
||||
return new Response(JSON.stringify({ status: 'success' }), {
|
||||
status: 200,
|
||||
headers: { 'Content-Type': 'application/json' }
|
||||
})
|
||||
}
|
||||
```
|
||||
|
||||
**Correct (non-blocking):**
|
||||
|
||||
```tsx
|
||||
import { after } from 'next/server'
|
||||
import { headers, cookies } from 'next/headers'
|
||||
import { logUserAction } from '@/app/utils'
|
||||
|
||||
export async function POST(request: Request) {
|
||||
// Perform mutation
|
||||
await updateDatabase(request)
|
||||
|
||||
// Log after response is sent
|
||||
after(async () => {
|
||||
const userAgent = (await headers()).get('user-agent') || 'unknown'
|
||||
const sessionCookie = (await cookies()).get('session-id')?.value || 'anonymous'
|
||||
|
||||
logUserAction({ sessionCookie, userAgent })
|
||||
})
|
||||
|
||||
return new Response(JSON.stringify({ status: 'success' }), {
|
||||
status: 200,
|
||||
headers: { 'Content-Type': 'application/json' }
|
||||
})
|
||||
}
|
||||
```
|
||||
|
||||
The response is sent immediately while logging happens in the background.
|
||||
|
||||
**Common use cases:**
|
||||
|
||||
- Analytics tracking
|
||||
- Audit logging
|
||||
- Sending notifications
|
||||
- Cache invalidation
|
||||
- Cleanup tasks
|
||||
|
||||
**Important notes:**
|
||||
|
||||
- `after()` runs even if the response fails or redirects
|
||||
- Works in Server Actions, Route Handlers, and Server Components
|
||||
|
||||
Reference: [https://nextjs.org/docs/app/api-reference/functions/after](https://nextjs.org/docs/app/api-reference/functions/after)
|
||||
@@ -1,96 +0,0 @@
|
||||
---
|
||||
title: Authenticate Server Actions Like API Routes
|
||||
impact: CRITICAL
|
||||
impactDescription: prevents unauthorized access to server mutations
|
||||
tags: server, server-actions, authentication, security, authorization
|
||||
---
|
||||
|
||||
## Authenticate Server Actions Like API Routes
|
||||
|
||||
**Impact: CRITICAL (prevents unauthorized access to server mutations)**
|
||||
|
||||
Server Actions (functions with `"use server"`) are exposed as public endpoints, just like API routes. Always verify authentication and authorization **inside** each Server Action—do not rely solely on middleware, layout guards, or page-level checks, as Server Actions can be invoked directly.
|
||||
|
||||
Next.js documentation explicitly states: "Treat Server Actions with the same security considerations as public-facing API endpoints, and verify if the user is allowed to perform a mutation."
|
||||
|
||||
**Incorrect (no authentication check):**
|
||||
|
||||
```typescript
|
||||
'use server'
|
||||
|
||||
export async function deleteUser(userId: string) {
|
||||
// Anyone can call this! No auth check
|
||||
await db.user.delete({ where: { id: userId } })
|
||||
return { success: true }
|
||||
}
|
||||
```
|
||||
|
||||
**Correct (authentication inside the action):**
|
||||
|
||||
```typescript
|
||||
'use server'
|
||||
|
||||
import { verifySession } from '@/lib/auth'
|
||||
import { unauthorized } from '@/lib/errors'
|
||||
|
||||
export async function deleteUser(userId: string) {
|
||||
// Always check auth inside the action
|
||||
const session = await verifySession()
|
||||
|
||||
if (!session) {
|
||||
throw unauthorized('Must be logged in')
|
||||
}
|
||||
|
||||
// Check authorization too
|
||||
if (session.user.role !== 'admin' && session.user.id !== userId) {
|
||||
throw unauthorized('Cannot delete other users')
|
||||
}
|
||||
|
||||
await db.user.delete({ where: { id: userId } })
|
||||
return { success: true }
|
||||
}
|
||||
```
|
||||
|
||||
**With input validation:**
|
||||
|
||||
```typescript
|
||||
'use server'
|
||||
|
||||
import { verifySession } from '@/lib/auth'
|
||||
import { z } from 'zod'
|
||||
|
||||
const updateProfileSchema = z.object({
|
||||
userId: z.string().uuid(),
|
||||
name: z.string().min(1).max(100),
|
||||
email: z.string().email()
|
||||
})
|
||||
|
||||
export async function updateProfile(data: unknown) {
|
||||
// Validate input first
|
||||
const validated = updateProfileSchema.parse(data)
|
||||
|
||||
// Then authenticate
|
||||
const session = await verifySession()
|
||||
if (!session) {
|
||||
throw new Error('Unauthorized')
|
||||
}
|
||||
|
||||
// Then authorize
|
||||
if (session.user.id !== validated.userId) {
|
||||
throw new Error('Can only update own profile')
|
||||
}
|
||||
|
||||
// Finally perform the mutation
|
||||
await db.user.update({
|
||||
where: { id: validated.userId },
|
||||
data: {
|
||||
name: validated.name,
|
||||
email: validated.email
|
||||
}
|
||||
})
|
||||
|
||||
return { success: true }
|
||||
}
|
||||
```
|
||||
|
||||
Reference: [https://nextjs.org/docs/app/guides/authentication](https://nextjs.org/docs/app/guides/authentication)
|
||||
@@ -1,41 +0,0 @@
|
||||
---
|
||||
title: Cross-Request LRU Caching
|
||||
impact: HIGH
|
||||
impactDescription: caches across requests
|
||||
tags: server, cache, lru, cross-request
|
||||
---
|
||||
|
||||
## Cross-Request LRU Caching
|
||||
|
||||
`React.cache()` only works within one request. For data shared across sequential requests (user clicks button A then button B), use an LRU cache.
|
||||
|
||||
**Implementation:**
|
||||
|
||||
```typescript
|
||||
import { LRUCache } from 'lru-cache'
|
||||
|
||||
const cache = new LRUCache<string, any>({
|
||||
max: 1000,
|
||||
ttl: 5 * 60 * 1000 // 5 minutes
|
||||
})
|
||||
|
||||
export async function getUser(id: string) {
|
||||
const cached = cache.get(id)
|
||||
if (cached) return cached
|
||||
|
||||
const user = await db.user.findUnique({ where: { id } })
|
||||
cache.set(id, user)
|
||||
return user
|
||||
}
|
||||
|
||||
// Request 1: DB query, result cached
|
||||
// Request 2: cache hit, no DB query
|
||||
```
|
||||
|
||||
Use when sequential user actions hit multiple endpoints needing the same data within seconds.
|
||||
|
||||
**With Vercel's [Fluid Compute](https://vercel.com/docs/fluid-compute):** LRU caching is especially effective because multiple concurrent requests can share the same function instance and cache. This means the cache persists across requests without needing external storage like Redis.
|
||||
|
||||
**In traditional serverless:** Each invocation runs in isolation, so consider Redis for cross-process caching.
|
||||
|
||||
Reference: [https://github.com/isaacs/node-lru-cache](https://github.com/isaacs/node-lru-cache)
|
||||
@@ -1,76 +0,0 @@
|
||||
---
|
||||
title: Per-Request Deduplication with React.cache()
|
||||
impact: MEDIUM
|
||||
impactDescription: deduplicates within request
|
||||
tags: server, cache, react-cache, deduplication
|
||||
---
|
||||
|
||||
## Per-Request Deduplication with React.cache()
|
||||
|
||||
Use `React.cache()` for server-side request deduplication. Authentication and database queries benefit most.
|
||||
|
||||
**Usage:**
|
||||
|
||||
```typescript
|
||||
import { cache } from 'react'
|
||||
|
||||
export const getCurrentUser = cache(async () => {
|
||||
const session = await auth()
|
||||
if (!session?.user?.id) return null
|
||||
return await db.user.findUnique({
|
||||
where: { id: session.user.id }
|
||||
})
|
||||
})
|
||||
```
|
||||
|
||||
Within a single request, multiple calls to `getCurrentUser()` execute the query only once.
|
||||
|
||||
**Avoid inline objects as arguments:**
|
||||
|
||||
`React.cache()` uses shallow equality (`Object.is`) to determine cache hits. Inline objects create new references each call, preventing cache hits.
|
||||
|
||||
**Incorrect (always cache miss):**
|
||||
|
||||
```typescript
|
||||
const getUser = cache(async (params: { uid: number }) => {
|
||||
return await db.user.findUnique({ where: { id: params.uid } })
|
||||
})
|
||||
|
||||
// Each call creates new object, never hits cache
|
||||
getUser({ uid: 1 })
|
||||
getUser({ uid: 1 }) // Cache miss, runs query again
|
||||
```
|
||||
|
||||
**Correct (cache hit):**
|
||||
|
||||
```typescript
|
||||
const getUser = cache(async (uid: number) => {
|
||||
return await db.user.findUnique({ where: { id: uid } })
|
||||
})
|
||||
|
||||
// Primitive args use value equality
|
||||
getUser(1)
|
||||
getUser(1) // Cache hit, returns cached result
|
||||
```
|
||||
|
||||
If you must pass objects, pass the same reference:
|
||||
|
||||
```typescript
|
||||
const params = { uid: 1 }
|
||||
getUser(params) // Query runs
|
||||
getUser(params) // Cache hit (same reference)
|
||||
```
|
||||
|
||||
**Next.js-Specific Note:**
|
||||
|
||||
In Next.js, the `fetch` API is automatically extended with request memoization. Requests with the same URL and options are automatically deduplicated within a single request, so you don't need `React.cache()` for `fetch` calls. However, `React.cache()` is still essential for other async tasks:
|
||||
|
||||
- Database queries (Prisma, Drizzle, etc.)
|
||||
- Heavy computations
|
||||
- Authentication checks
|
||||
- File system operations
|
||||
- Any non-fetch async work
|
||||
|
||||
Use `React.cache()` to deduplicate these operations across your component tree.
|
||||
|
||||
Reference: [React.cache documentation](https://react.dev/reference/react/cache)
|
||||
@@ -1,65 +0,0 @@
|
||||
---
|
||||
title: Avoid Duplicate Serialization in RSC Props
|
||||
impact: LOW
|
||||
impactDescription: reduces network payload by avoiding duplicate serialization
|
||||
tags: server, rsc, serialization, props, client-components
|
||||
---
|
||||
|
||||
## Avoid Duplicate Serialization in RSC Props
|
||||
|
||||
**Impact: LOW (reduces network payload by avoiding duplicate serialization)**
|
||||
|
||||
RSC→client serialization deduplicates by object reference, not value. Same reference = serialized once; new reference = serialized again. Do transformations (`.toSorted()`, `.filter()`, `.map()`) in client, not server.
|
||||
|
||||
**Incorrect (duplicates array):**
|
||||
|
||||
```tsx
|
||||
// RSC: sends 6 strings (2 arrays × 3 items)
|
||||
<ClientList usernames={usernames} usernamesOrdered={usernames.toSorted()} />
|
||||
```
|
||||
|
||||
**Correct (sends 3 strings):**
|
||||
|
||||
```tsx
|
||||
// RSC: send once
|
||||
<ClientList usernames={usernames} />
|
||||
|
||||
// Client: transform there
|
||||
'use client'
|
||||
const sorted = useMemo(() => [...usernames].sort(), [usernames])
|
||||
```
|
||||
|
||||
**Nested deduplication behavior:**
|
||||
|
||||
Deduplication works recursively. Impact varies by data type:
|
||||
|
||||
- `string[]`, `number[]`, `boolean[]`: **HIGH impact** - array + all primitives fully duplicated
|
||||
- `object[]`: **LOW impact** - array duplicated, but nested objects deduplicated by reference
|
||||
|
||||
```tsx
|
||||
// string[] - duplicates everything
|
||||
usernames={['a','b']} sorted={usernames.toSorted()} // sends 4 strings
|
||||
|
||||
// object[] - duplicates array structure only
|
||||
users={[{id:1},{id:2}]} sorted={users.toSorted()} // sends 2 arrays + 2 unique objects (not 4)
|
||||
```
|
||||
|
||||
**Operations breaking deduplication (create new references):**
|
||||
|
||||
- Arrays: `.toSorted()`, `.filter()`, `.map()`, `.slice()`, `[...arr]`
|
||||
- Objects: `{...obj}`, `Object.assign()`, `structuredClone()`, `JSON.parse(JSON.stringify())`
|
||||
|
||||
**More examples:**
|
||||
|
||||
```tsx
|
||||
// ❌ Bad
|
||||
<C users={users} active={users.filter(u => u.active)} />
|
||||
<C product={product} productName={product.name} />
|
||||
|
||||
// ✅ Good
|
||||
<C users={users} />
|
||||
<C product={product} />
|
||||
// Do filtering/destructuring in client
|
||||
```
|
||||
|
||||
**Exception:** Pass derived data when transformation is expensive or client doesn't need original.
|
||||
@@ -1,149 +0,0 @@
|
||||
---
|
||||
title: Hoist Static I/O to Module Level
|
||||
impact: HIGH
|
||||
impactDescription: avoids repeated file/network I/O per request
|
||||
tags: server, io, performance, next.js, route-handlers, og-image
|
||||
---
|
||||
|
||||
## Hoist Static I/O to Module Level
|
||||
|
||||
**Impact: HIGH (avoids repeated file/network I/O per request)**
|
||||
|
||||
When loading static assets (fonts, logos, images, config files) in route handlers or server functions, hoist the I/O operation to module level. Module-level code runs once when the module is first imported, not on every request. This eliminates redundant file system reads or network fetches that would otherwise run on every invocation.
|
||||
|
||||
**Incorrect (reads font file on every request):**
|
||||
|
||||
```typescript
|
||||
// app/api/og/route.tsx
|
||||
import { ImageResponse } from 'next/og'
|
||||
|
||||
export async function GET(request: Request) {
|
||||
// Runs on EVERY request - expensive!
|
||||
const fontData = await fetch(
|
||||
new URL('./fonts/Inter.ttf', import.meta.url)
|
||||
).then(res => res.arrayBuffer())
|
||||
|
||||
const logoData = await fetch(
|
||||
new URL('./images/logo.png', import.meta.url)
|
||||
).then(res => res.arrayBuffer())
|
||||
|
||||
return new ImageResponse(
|
||||
<div style={{ fontFamily: 'Inter' }}>
|
||||
<img src={logoData} />
|
||||
Hello World
|
||||
</div>,
|
||||
{ fonts: [{ name: 'Inter', data: fontData }] }
|
||||
)
|
||||
}
|
||||
```
|
||||
|
||||
**Correct (loads once at module initialization):**
|
||||
|
||||
```typescript
|
||||
// app/api/og/route.tsx
|
||||
import { ImageResponse } from 'next/og'
|
||||
|
||||
// Module-level: runs ONCE when module is first imported
|
||||
const fontData = fetch(
|
||||
new URL('./fonts/Inter.ttf', import.meta.url)
|
||||
).then(res => res.arrayBuffer())
|
||||
|
||||
const logoData = fetch(
|
||||
new URL('./images/logo.png', import.meta.url)
|
||||
).then(res => res.arrayBuffer())
|
||||
|
||||
export async function GET(request: Request) {
|
||||
// Await the already-started promises
|
||||
const [font, logo] = await Promise.all([fontData, logoData])
|
||||
|
||||
return new ImageResponse(
|
||||
<div style={{ fontFamily: 'Inter' }}>
|
||||
<img src={logo} />
|
||||
Hello World
|
||||
</div>,
|
||||
{ fonts: [{ name: 'Inter', data: font }] }
|
||||
)
|
||||
}
|
||||
```
|
||||
|
||||
**Correct (synchronous fs at module level):**
|
||||
|
||||
```typescript
|
||||
// app/api/og/route.tsx
|
||||
import { ImageResponse } from 'next/og'
|
||||
import { readFileSync } from 'fs'
|
||||
import { join } from 'path'
|
||||
|
||||
// Synchronous read at module level - blocks only during module init
|
||||
const fontData = readFileSync(
|
||||
join(process.cwd(), 'public/fonts/Inter.ttf')
|
||||
)
|
||||
|
||||
const logoData = readFileSync(
|
||||
join(process.cwd(), 'public/images/logo.png')
|
||||
)
|
||||
|
||||
export async function GET(request: Request) {
|
||||
return new ImageResponse(
|
||||
<div style={{ fontFamily: 'Inter' }}>
|
||||
<img src={logoData} />
|
||||
Hello World
|
||||
</div>,
|
||||
{ fonts: [{ name: 'Inter', data: fontData }] }
|
||||
)
|
||||
}
|
||||
```
|
||||
|
||||
**Incorrect (reads config on every call):**
|
||||
|
||||
```typescript
|
||||
import fs from 'node:fs/promises'
|
||||
|
||||
export async function processRequest(data: Data) {
|
||||
const config = JSON.parse(
|
||||
await fs.readFile('./config.json', 'utf-8')
|
||||
)
|
||||
const template = await fs.readFile('./template.html', 'utf-8')
|
||||
|
||||
return render(template, data, config)
|
||||
}
|
||||
```
|
||||
|
||||
**Correct (hoists config and template to module level):**
|
||||
|
||||
```typescript
|
||||
import fs from 'node:fs/promises'
|
||||
|
||||
const configPromise = fs
|
||||
.readFile('./config.json', 'utf-8')
|
||||
.then(JSON.parse)
|
||||
const templatePromise = fs.readFile('./template.html', 'utf-8')
|
||||
|
||||
export async function processRequest(data: Data) {
|
||||
const [config, template] = await Promise.all([
|
||||
configPromise,
|
||||
templatePromise,
|
||||
])
|
||||
|
||||
return render(template, data, config)
|
||||
}
|
||||
```
|
||||
|
||||
When to use this pattern:
|
||||
|
||||
- Loading fonts for OG image generation
|
||||
- Loading static logos, icons, or watermarks
|
||||
- Reading configuration files that don't change at runtime
|
||||
- Loading email templates or other static templates
|
||||
- Any static asset that's the same across all requests
|
||||
|
||||
When not to use this pattern:
|
||||
|
||||
- Assets that vary per request or user
|
||||
- Files that may change during runtime (use caching with TTL instead)
|
||||
- Large files that would consume too much memory if kept loaded
|
||||
- Sensitive data that shouldn't persist in memory
|
||||
|
||||
With Vercel's [Fluid Compute](https://vercel.com/docs/fluid-compute), module-level caching is especially effective because multiple concurrent requests share the same function instance. The static assets stay loaded in memory across requests without cold start penalties.
|
||||
|
||||
In traditional serverless, each cold start re-executes module-level code, but subsequent warm invocations reuse the loaded assets until the instance is recycled.
|
||||
@@ -1,50 +0,0 @@
|
||||
---
|
||||
title: Avoid Shared Module State for Request Data
|
||||
impact: HIGH
|
||||
impactDescription: prevents concurrency bugs and request data leaks
|
||||
tags: server, rsc, ssr, concurrency, security, state
|
||||
---
|
||||
|
||||
## Avoid Shared Module State for Request Data
|
||||
|
||||
For React Server Components and client components rendered during SSR, avoid using mutable module-level variables to share request-scoped data. Server renders can run concurrently in the same process. If one render writes to shared module state and another render reads it, you can get race conditions, cross-request contamination, and security bugs where one user's data appears in another user's response.
|
||||
|
||||
Treat module scope on the server as process-wide shared memory, not request-local state.
|
||||
|
||||
**Incorrect (request data leaks across concurrent renders):**
|
||||
|
||||
```tsx
|
||||
let currentUser: User | null = null
|
||||
|
||||
export default async function Page() {
|
||||
currentUser = await auth()
|
||||
return <Dashboard />
|
||||
}
|
||||
|
||||
async function Dashboard() {
|
||||
return <div>{currentUser?.name}</div>
|
||||
}
|
||||
```
|
||||
|
||||
If two requests overlap, request A can set `currentUser`, then request B overwrites it before request A finishes rendering `Dashboard`.
|
||||
|
||||
**Correct (keep request data local to the render tree):**
|
||||
|
||||
```tsx
|
||||
export default async function Page() {
|
||||
const user = await auth()
|
||||
return <Dashboard user={user} />
|
||||
}
|
||||
|
||||
function Dashboard({ user }: { user: User | null }) {
|
||||
return <div>{user?.name}</div>
|
||||
}
|
||||
```
|
||||
|
||||
Safe exceptions:
|
||||
|
||||
- Immutable static assets or config loaded once at module scope
|
||||
- Shared caches intentionally designed for cross-request reuse and keyed correctly
|
||||
- Process-wide singletons that do not store request- or user-specific mutable data
|
||||
|
||||
For static assets and config, see [Hoist Static I/O to Module Level](./server-hoist-static-io.md).
|
||||
@@ -1,83 +0,0 @@
|
||||
---
|
||||
title: Parallel Data Fetching with Component Composition
|
||||
impact: CRITICAL
|
||||
impactDescription: eliminates server-side waterfalls
|
||||
tags: server, rsc, parallel-fetching, composition
|
||||
---
|
||||
|
||||
## Parallel Data Fetching with Component Composition
|
||||
|
||||
React Server Components execute sequentially within a tree. Restructure with composition to parallelize data fetching.
|
||||
|
||||
**Incorrect (Sidebar waits for Page's fetch to complete):**
|
||||
|
||||
```tsx
|
||||
export default async function Page() {
|
||||
const header = await fetchHeader()
|
||||
return (
|
||||
<div>
|
||||
<div>{header}</div>
|
||||
<Sidebar />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
async function Sidebar() {
|
||||
const items = await fetchSidebarItems()
|
||||
return <nav>{items.map(renderItem)}</nav>
|
||||
}
|
||||
```
|
||||
|
||||
**Correct (both fetch simultaneously):**
|
||||
|
||||
```tsx
|
||||
async function Header() {
|
||||
const data = await fetchHeader()
|
||||
return <div>{data}</div>
|
||||
}
|
||||
|
||||
async function Sidebar() {
|
||||
const items = await fetchSidebarItems()
|
||||
return <nav>{items.map(renderItem)}</nav>
|
||||
}
|
||||
|
||||
export default function Page() {
|
||||
return (
|
||||
<div>
|
||||
<Header />
|
||||
<Sidebar />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
```
|
||||
|
||||
**Alternative with children prop:**
|
||||
|
||||
```tsx
|
||||
async function Header() {
|
||||
const data = await fetchHeader()
|
||||
return <div>{data}</div>
|
||||
}
|
||||
|
||||
async function Sidebar() {
|
||||
const items = await fetchSidebarItems()
|
||||
return <nav>{items.map(renderItem)}</nav>
|
||||
}
|
||||
|
||||
function Layout({ children }: { children: ReactNode }) {
|
||||
return (
|
||||
<div>
|
||||
<Header />
|
||||
{children}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export default function Page() {
|
||||
return (
|
||||
<Layout>
|
||||
<Sidebar />
|
||||
</Layout>
|
||||
)
|
||||
}
|
||||
```
|
||||
-34
@@ -1,34 +0,0 @@
|
||||
---
|
||||
title: Parallel Nested Data Fetching
|
||||
impact: CRITICAL
|
||||
impactDescription: eliminates server-side waterfalls
|
||||
tags: server, rsc, parallel-fetching, promise-chaining
|
||||
---
|
||||
|
||||
## Parallel Nested Data Fetching
|
||||
|
||||
When fetching nested data in parallel, chain dependent fetches within each item's promise so a slow item doesn't block the rest.
|
||||
|
||||
**Incorrect (a single slow item blocks all nested fetches):**
|
||||
|
||||
```tsx
|
||||
const chats = await Promise.all(
|
||||
chatIds.map(id => getChat(id))
|
||||
)
|
||||
|
||||
const chatAuthors = await Promise.all(
|
||||
chats.map(chat => getUser(chat.author))
|
||||
)
|
||||
```
|
||||
|
||||
If one `getChat(id)` out of 100 is extremely slow, the authors of the other 99 chats can't start loading even though their data is ready.
|
||||
|
||||
**Correct (each item chains its own nested fetch):**
|
||||
|
||||
```tsx
|
||||
const chatAuthors = await Promise.all(
|
||||
chatIds.map(id => getChat(id).then(chat => getUser(chat.author)))
|
||||
)
|
||||
```
|
||||
|
||||
Each item independently chains `getChat` → `getUser`, so a slow chat doesn't block author fetches for the others.
|
||||
@@ -1,38 +0,0 @@
|
||||
---
|
||||
title: Minimize Serialization at RSC Boundaries
|
||||
impact: HIGH
|
||||
impactDescription: reduces data transfer size
|
||||
tags: server, rsc, serialization, props
|
||||
---
|
||||
|
||||
## Minimize Serialization at RSC Boundaries
|
||||
|
||||
The React Server/Client boundary serializes all object properties into strings and embeds them in the HTML response and subsequent RSC requests. This serialized data directly impacts page weight and load time, so **size matters a lot**. Only pass fields that the client actually uses.
|
||||
|
||||
**Incorrect (serializes all 50 fields):**
|
||||
|
||||
```tsx
|
||||
async function Page() {
|
||||
const user = await fetchUser() // 50 fields
|
||||
return <Profile user={user} />
|
||||
}
|
||||
|
||||
'use client'
|
||||
function Profile({ user }: { user: User }) {
|
||||
return <div>{user.name}</div> // uses 1 field
|
||||
}
|
||||
```
|
||||
|
||||
**Correct (serializes only 1 field):**
|
||||
|
||||
```tsx
|
||||
async function Page() {
|
||||
const user = await fetchUser()
|
||||
return <Profile name={user.name} />
|
||||
}
|
||||
|
||||
'use client'
|
||||
function Profile({ name }: { name: string }) {
|
||||
return <div>{name}</div>
|
||||
}
|
||||
```
|
||||
@@ -1,123 +0,0 @@
|
||||
# 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).
|
||||
@@ -1,15 +0,0 @@
|
||||
{
|
||||
"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"
|
||||
]
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,157 +0,0 @@
|
||||
---
|
||||
name: remotion-best-practices
|
||||
description: Use when writing, reviewing, or refactoring Remotion code in this repository, including compositions, dynamic metadata, @remotion/media video/audio, CLI or renderer rendering, Docker/Chromium settings, queue progress/cancellation, or render performance.
|
||||
---
|
||||
|
||||
# Remotion Best Practices
|
||||
|
||||
## Overview
|
||||
|
||||
Apply current Remotion guidance to this Bun rendering service without losing the
|
||||
project-specific details that make renders reliable: dynamic metadata, S3 input
|
||||
URLs, BullMQ progress, Docker Chromium, and cleanup of generated artifacts.
|
||||
|
||||
## Workflow
|
||||
|
||||
1. Fetch current Remotion docs first with Context7. This repo pins Remotion
|
||||
packages at `4.0.435`, so compare docs version badges against that version
|
||||
before using newer API options.
|
||||
2. Identify the layer being changed:
|
||||
- Composition UI: `src/components/Composition.tsx`, `src/components/Captions.tsx`
|
||||
- Composition registration and metadata: `src/components/Root.tsx`,
|
||||
`src/hooks/useVideoMeta.ts`
|
||||
- Render orchestration: `server/services/render_video.ts`,
|
||||
`server/services/render_queue.ts`
|
||||
- Runtime config: `remotion.config.ts`, `Dockerfile`, `.env.example`,
|
||||
`server/config.ts`
|
||||
3. Keep render behavior deterministic. A frame should be a pure function of
|
||||
props, frame number, and explicitly loaded assets.
|
||||
4. Verify with `bun run lint` and a focused smoke test: Remotion Studio,
|
||||
`bun run render` with valid props, or the API/queue path when server behavior
|
||||
changed.
|
||||
|
||||
## Project Map
|
||||
|
||||
- Runtime: Bun, React 19, Remotion `4.0.435`.
|
||||
- Entry point: `src/index.ts` registers `RemotionRoot`.
|
||||
- Main composition: `CaptionedVideo` in `src/components/Root.tsx`.
|
||||
- Metadata: `getVideoMeta()` uses `calculateMetadata` plus
|
||||
`@remotion/media-parser` `parseMedia()` to set duration, dimensions, and fps
|
||||
from the input video.
|
||||
- Media rendering: `CaptionsComposition` uses `@remotion/media` `Video`, with
|
||||
captions overlaid in `AbsoluteFill`.
|
||||
- Server rendering: `renderCaptionedVideo()` writes props JSON into `out/`,
|
||||
runs `./node_modules/.bin/remotion render src/index.ts ... --props`, parses
|
||||
CLI progress output, and deletes the props file in `finally`.
|
||||
- Queue wrapper: BullMQ controls job concurrency through
|
||||
`MAX_CONCURRENT_RENDERS`, uploads finished files to S3, sends webhooks, and
|
||||
stores cancellation flags in Redis.
|
||||
- Docker: Chromium and FFmpeg are installed in the image; Remotion browser
|
||||
download is skipped; sandboxing is disabled through env.
|
||||
|
||||
## Composition Rules
|
||||
|
||||
- Animate with `useCurrentFrame()`, `useVideoConfig()`, `interpolate()`,
|
||||
`spring()`, and `Sequence`. Do not use CSS animations, CSS transitions,
|
||||
timers, or wall-clock time for render-critical motion.
|
||||
- Keep props JSON-serializable. When adding composition input fields, update
|
||||
`src/types/captions_composition.d.ts`, `src/components/Root.tsx`
|
||||
`defaultProps`, and the server-side props object together.
|
||||
- Avoid fetches or expensive async work inside frame-rendering components.
|
||||
Prefer server preprocessing or `calculateMetadata()` for data that changes
|
||||
duration, dimensions, fps, or props.
|
||||
- Use `delayRender()` only for assets that must block a frame, such as dynamic
|
||||
CSS/font loading. In new code prefer `useDelayRender()` where practical, and
|
||||
always clear or cancel every handle on success and failure.
|
||||
- Use `AbsoluteFill` for full-frame layers and `Sequence` for frame-based
|
||||
timing. Convert seconds with the active `fps`, not a hardcoded 30 unless the
|
||||
composition contract really is fixed at 30 fps.
|
||||
|
||||
## Metadata
|
||||
|
||||
- Keep dynamic duration and dimensions in `calculateMetadata`, not component
|
||||
`useEffect()`. In Remotion v4, `useEffect()` can run again for render workers
|
||||
and multiply API calls.
|
||||
- For this repo, preserve the existing `parseMedia()` path unless deliberately
|
||||
upgrading. Current Remotion docs are moving media metadata toward Mediabunny,
|
||||
so check docs before adding new metadata helpers.
|
||||
- Use `Math.ceil(durationInSeconds * fps)` and keep the existing minimum of one
|
||||
frame so zero-length or partially unreadable metadata cannot produce invalid
|
||||
compositions.
|
||||
- If metadata fetching starts using `fetch()`, pass Remotion's `abortSignal` so
|
||||
cancelled metadata calculations stop promptly.
|
||||
- When migrating from the CLI to `@remotion/renderer`, pass the same
|
||||
`inputProps` to both `selectComposition()` and `renderMedia()` so
|
||||
`calculateMetadata()` and the actual render resolve the same composition.
|
||||
|
||||
## Media And Assets
|
||||
|
||||
- Local reusable assets belong in `public/` and should be referenced with
|
||||
`staticFile()`. The `public/` folder must stay beside the project
|
||||
`package.json`.
|
||||
- Remote video URLs from S3/MinIO are valid, but they must be accessible from
|
||||
the Chromium process inside Docker. Prefer presigned URLs with enough TTL for
|
||||
queue wait time plus render time.
|
||||
- This repo currently uses `@remotion/media` `Video`. It is frame-perfect and
|
||||
fast, but respect version badges: options introduced after `4.0.435` require
|
||||
a package upgrade before use.
|
||||
- Do not use `objectFit` on `@remotion/media` `Video` while the project remains
|
||||
on `4.0.435`; the docs mark it as `4.0.442`. Use sizing wrappers or upgrade
|
||||
Remotion intentionally.
|
||||
- Do not use `credentials` on `@remotion/media` `Video` while on `4.0.435`; the
|
||||
docs mark it as `4.0.437`. Prefer signed public URLs for protected videos in
|
||||
this version.
|
||||
- Keep `Config.setVideoImageFormat("jpeg")` for regular opaque videos. Switch
|
||||
to `png` only when transparency or color-accuracy requirements justify the
|
||||
slower render and larger intermediate frames.
|
||||
- For unsupported media, HLS, looping, alpha channels, pitch shifts, or
|
||||
frame-manipulation callbacks, re-check the current docs for `@remotion/media`
|
||||
`Video`, `OffthreadVideo`, and their fallback behavior before changing code.
|
||||
|
||||
## Render Service Rules
|
||||
|
||||
- The current CLI path means `remotion.config.ts` applies. If switching to
|
||||
Node/Bun APIs, move needed options into `bundle()`, `selectComposition()`, or
|
||||
`renderMedia()` because Remotion config is not automatically applied there.
|
||||
- Keep the two concurrency knobs separate:
|
||||
- BullMQ `MAX_CONCURRENT_RENDERS` controls simultaneous videos.
|
||||
- Remotion render concurrency controls frame workers inside one video.
|
||||
Tune both against Docker CPU and memory limits; a 4 GB / 2 CPU container can
|
||||
run out of memory quickly with multiple video jobs.
|
||||
- Prefer renderer callbacks (`onStart`, `onProgress`, `onBrowserLog`,
|
||||
`onDownload`) if moving to `@remotion/renderer`. Keep CLI progress parsing
|
||||
tolerant because CLI log text can change.
|
||||
- If moving to `@remotion/renderer`, use `makeCancelSignal()` instead of only
|
||||
killing a process. Keep Redis cancellation and upload abort behavior aligned.
|
||||
- Preserve bounded stdout/stderr capture. Render failures should include enough
|
||||
tail output for debugging without logging full user media paths or huge logs.
|
||||
- Keep generated files under `out/`, remove props JSON in `finally`, and remove
|
||||
rendered files after upload. Never commit render outputs or real `.env`
|
||||
values.
|
||||
- In Docker, keep Chromium, FFmpeg, emoji fonts, and Linux browser libraries in
|
||||
sync with Remotion requirements. If browser detection changes, configure an
|
||||
explicit browser executable or Remotion renderer option instead of relying on
|
||||
accidental host state.
|
||||
|
||||
## Validation
|
||||
|
||||
- Always run `bun run lint` after TypeScript or Remotion changes.
|
||||
- For composition/caption layout changes, run Remotion Studio or a short render
|
||||
using valid props with an accessible `videoSrc`.
|
||||
- For API, queue, cancellation, or upload changes, run `bun run server` and
|
||||
smoke the affected `/api/render` flow, including callback/progress behavior
|
||||
when touched.
|
||||
- For Docker/browser/render-performance changes, smoke through
|
||||
`docker compose up --build remotion` when feasible because local host Chrome
|
||||
behavior is not enough evidence.
|
||||
|
||||
## Source Anchors
|
||||
|
||||
- Remotion render APIs: https://www.remotion.dev/docs/renderer/render-media
|
||||
- Dynamic metadata: https://www.remotion.dev/docs/dynamic-metadata
|
||||
- `delayRender()` / `useDelayRender()`: https://www.remotion.dev/docs/delay-render
|
||||
- Video tag comparison: https://www.remotion.dev/docs/video-tags
|
||||
- `@remotion/media` `Video`: https://www.remotion.dev/docs/media/video
|
||||
- `staticFile()`: https://www.remotion.dev/docs/staticfile
|
||||
- Server-side rendering and Docker links: https://www.remotion.dev/docs/ssr
|
||||
- Official Remotion agent skills: https://www.remotion.dev/docs/ai/skills
|
||||
@@ -1,4 +0,0 @@
|
||||
interface:
|
||||
display_name: "Remotion Best Practices"
|
||||
short_description: "Guide Remotion rendering changes in this service."
|
||||
default_prompt: "Use $remotion-best-practices when changing Remotion compositions, metadata, or rendering service code."
|
||||
@@ -1,373 +0,0 @@
|
||||
---
|
||||
name: typescript-best-practices
|
||||
description:
|
||||
Modern TypeScript patterns your AI agent should use. Strict mode, discriminated unions, satisfies
|
||||
operator, const assertions, and type-safe patterns for TypeScript 5.x.
|
||||
metadata:
|
||||
tags: typescript, type-safety, best-practices
|
||||
---
|
||||
|
||||
## When to use
|
||||
|
||||
Use this skill when working with TypeScript code. AI agents frequently generate outdated patterns -
|
||||
using `any` instead of `unknown`, type assertions instead of `satisfies`, optional fields instead of
|
||||
discriminated unions, and missing strict mode options. This skill enforces modern TypeScript 5.x
|
||||
patterns.
|
||||
|
||||
## Critical Rules
|
||||
|
||||
### 1. Enable Strict Mode with All Checks
|
||||
|
||||
**Wrong (agents do this):**
|
||||
|
||||
```json
|
||||
{
|
||||
"compilerOptions": {
|
||||
"strict": false,
|
||||
"target": "ES2020"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**Correct:**
|
||||
|
||||
```json
|
||||
{
|
||||
"compilerOptions": {
|
||||
"strict": true,
|
||||
"noUncheckedIndexedAccess": true,
|
||||
"exactOptionalPropertyTypes": true,
|
||||
"noImplicitOverride": true,
|
||||
"target": "ES2022"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**Why:** Strict mode catches entire categories of bugs. `noUncheckedIndexedAccess` prevents unsafe
|
||||
array/object access. Agents often skip these for "convenience."
|
||||
|
||||
### 2. Use satisfies Instead of Type Assertions
|
||||
|
||||
**Wrong (agents do this):**
|
||||
|
||||
```typescript
|
||||
const config = {
|
||||
port: 3000,
|
||||
host: "localhost",
|
||||
} as Config;
|
||||
|
||||
config.port.toFixed(); // No error even if port could be string
|
||||
```
|
||||
|
||||
**Correct:**
|
||||
|
||||
```typescript
|
||||
const config = {
|
||||
port: 3000,
|
||||
host: "localhost",
|
||||
} satisfies Config;
|
||||
|
||||
config.port.toFixed(); // TypeScript knows port is number
|
||||
```
|
||||
|
||||
**Why:** `satisfies` validates the type without widening it. `as` silences the compiler and can hide
|
||||
bugs. Use `satisfies` for validation, `as` only when you genuinely know more than the compiler.
|
||||
|
||||
### 3. Use Discriminated Unions Over Optional Fields
|
||||
|
||||
**Wrong (agents do this):**
|
||||
|
||||
```typescript
|
||||
interface ApiResponse {
|
||||
data?: User;
|
||||
error?: string;
|
||||
loading?: boolean;
|
||||
}
|
||||
```
|
||||
|
||||
**Correct:**
|
||||
|
||||
```typescript
|
||||
type ApiResponse =
|
||||
| { status: "loading" }
|
||||
| { status: "success"; data: User }
|
||||
| { status: "error"; error: string };
|
||||
```
|
||||
|
||||
**Why:** Optional fields allow impossible states (data AND error both present). Discriminated unions
|
||||
make each state explicit and exhaustively checkable.
|
||||
|
||||
### 4. Use const Assertions for Literal Types
|
||||
|
||||
**Wrong (agents do this):**
|
||||
|
||||
```typescript
|
||||
const ROUTES = {
|
||||
home: "/",
|
||||
about: "/about",
|
||||
contact: "/contact",
|
||||
};
|
||||
// Type: { home: string; about: string; contact: string }
|
||||
```
|
||||
|
||||
**Correct:**
|
||||
|
||||
```typescript
|
||||
const ROUTES = {
|
||||
home: "/",
|
||||
about: "/about",
|
||||
contact: "/contact",
|
||||
} as const;
|
||||
// Type: { readonly home: "/"; readonly about: "/about"; readonly contact: "/contact" }
|
||||
```
|
||||
|
||||
**Why:** Without `as const`, TypeScript widens literal types to `string`. With it, you get exact
|
||||
literal types and readonly properties.
|
||||
|
||||
### 5. Use unknown Instead of any
|
||||
|
||||
**Wrong (agents do this):**
|
||||
|
||||
```typescript
|
||||
function parseJson(text: string): any {
|
||||
return JSON.parse(text);
|
||||
}
|
||||
|
||||
const data = parseJson('{"name": "test"}');
|
||||
data.nonExistent.method(); // No error - runtime crash
|
||||
```
|
||||
|
||||
**Correct:**
|
||||
|
||||
```typescript
|
||||
function parseJson(text: string): unknown {
|
||||
return JSON.parse(text);
|
||||
}
|
||||
|
||||
const data = parseJson('{"name": "test"}');
|
||||
if (isUser(data)) {
|
||||
data.name; // Safe - type narrowed
|
||||
}
|
||||
```
|
||||
|
||||
**Why:** `any` disables all type checking. `unknown` forces you to narrow the type before using it,
|
||||
catching bugs at compile time.
|
||||
|
||||
### 6. Use Template Literal Types for String Patterns
|
||||
|
||||
**Wrong (agents do this):**
|
||||
|
||||
```typescript
|
||||
function getLocaleMessage(id: string): string { ... }
|
||||
```
|
||||
|
||||
**Correct:**
|
||||
|
||||
```typescript
|
||||
type Locale = 'en' | 'ja' | 'pt';
|
||||
type MessageKey = 'welcome' | 'goodbye';
|
||||
type LocaleMessageId = `${Locale}_${MessageKey}`;
|
||||
|
||||
function getLocaleMessage(id: LocaleMessageId): string { ... }
|
||||
```
|
||||
|
||||
**Why:** Template literal types create precise string patterns from unions. The compiler catches
|
||||
typos and invalid combinations at build time.
|
||||
|
||||
### 7. Use NoInfer to Prevent Unwanted Inference
|
||||
|
||||
**Wrong (agents do this):**
|
||||
|
||||
```typescript
|
||||
function createLight<C extends string>(colors: C[], defaultColor?: C) { ... }
|
||||
createLight(['red', 'green', 'blue'], 'purple'); // No error - purple widens C
|
||||
```
|
||||
|
||||
**Correct:**
|
||||
|
||||
```typescript
|
||||
function createLight<C extends string>(colors: C[], defaultColor?: NoInfer<C>) { ... }
|
||||
createLight(['red', 'green', 'blue'], 'purple'); // Error - 'purple' not in C
|
||||
```
|
||||
|
||||
**Why:** `NoInfer<T>` (TypeScript 5.4+) prevents a parameter from influencing type inference,
|
||||
ensuring stricter checks.
|
||||
|
||||
### 8. Use Branded Types for Type-Safe IDs
|
||||
|
||||
**Wrong (agents do this):**
|
||||
|
||||
```typescript
|
||||
function getUser(id: string): User { ... }
|
||||
function getOrder(id: string): Order { ... }
|
||||
|
||||
const userId = getUserId();
|
||||
getOrder(userId); // No error - but wrong!
|
||||
```
|
||||
|
||||
**Correct:**
|
||||
|
||||
```typescript
|
||||
type UserId = string & { readonly __brand: 'UserId' };
|
||||
type OrderId = string & { readonly __brand: 'OrderId' };
|
||||
|
||||
function getUser(id: UserId): User { ... }
|
||||
function getOrder(id: OrderId): Order { ... }
|
||||
|
||||
const userId = getUserId();
|
||||
getOrder(userId); // Error - UserId is not OrderId
|
||||
```
|
||||
|
||||
**Why:** Branded types prevent accidentally passing one ID type where another is expected. The brand
|
||||
exists only at compile time - zero runtime cost.
|
||||
|
||||
### 9. Use Exhaustive Switch with never
|
||||
|
||||
**Wrong (agents do this):**
|
||||
|
||||
```typescript
|
||||
function handleStatus(status: "active" | "inactive" | "pending") {
|
||||
switch (status) {
|
||||
case "active":
|
||||
return "Active";
|
||||
case "inactive":
|
||||
return "Inactive";
|
||||
// 'pending' silently falls through
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**Correct:**
|
||||
|
||||
```typescript
|
||||
function handleStatus(status: "active" | "inactive" | "pending") {
|
||||
switch (status) {
|
||||
case "active":
|
||||
return "Active";
|
||||
case "inactive":
|
||||
return "Inactive";
|
||||
case "pending":
|
||||
return "Pending";
|
||||
default: {
|
||||
const _exhaustive: never = status;
|
||||
throw new Error(`Unhandled status: ${_exhaustive}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**Why:** The `never` check ensures every union member is handled. When a new status is added, the
|
||||
compiler flags the missing case.
|
||||
|
||||
### 10. Use Type Predicates Over Type Assertions
|
||||
|
||||
**Wrong (agents do this):**
|
||||
|
||||
```typescript
|
||||
function processItem(item: unknown) {
|
||||
const user = item as User;
|
||||
console.log(user.name);
|
||||
}
|
||||
```
|
||||
|
||||
**Correct:**
|
||||
|
||||
```typescript
|
||||
function isUser(item: unknown): item is User {
|
||||
return typeof item === "object" && item !== null && "name" in item && "email" in item;
|
||||
}
|
||||
|
||||
function processItem(item: unknown) {
|
||||
if (isUser(item)) {
|
||||
console.log(item.name); // Safe - narrowed to User
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**Why:** Type predicates (`item is User`) narrow types safely with runtime checks. Type assertions
|
||||
(`as User`) bypass the compiler and can hide bugs.
|
||||
|
||||
### 11. Use import type for Type-Only Imports
|
||||
|
||||
**Wrong (agents do this):**
|
||||
|
||||
```typescript
|
||||
import { User, UserService } from "./user";
|
||||
// User is only used as a type, but gets included in the bundle
|
||||
```
|
||||
|
||||
**Correct:**
|
||||
|
||||
```typescript
|
||||
import type { User } from "./user";
|
||||
import { UserService } from "./user";
|
||||
```
|
||||
|
||||
**Why:** `import type` is erased at compile time, reducing bundle size. It also makes the intent
|
||||
clear - this import is for types only.
|
||||
|
||||
### 12. Use Record Over Index Signatures
|
||||
|
||||
**Wrong (agents do this):**
|
||||
|
||||
```typescript
|
||||
interface Config {
|
||||
[key: string]: string;
|
||||
}
|
||||
```
|
||||
|
||||
**Correct:**
|
||||
|
||||
```typescript
|
||||
type Config = Record<string, string>;
|
||||
|
||||
// Or better - use a specific union for keys:
|
||||
type Config = Record<"host" | "port" | "env", string>;
|
||||
```
|
||||
|
||||
**Why:** `Record<K, V>` is more readable and composable than index signatures. When possible, use a
|
||||
union for keys to get exhaustive checking.
|
||||
|
||||
### 13. Use using for Resource Management
|
||||
|
||||
**Wrong (agents do this):**
|
||||
|
||||
```typescript
|
||||
const file = openFile("data.txt");
|
||||
try {
|
||||
processFile(file);
|
||||
} finally {
|
||||
file.close();
|
||||
}
|
||||
```
|
||||
|
||||
**Correct:**
|
||||
|
||||
```typescript
|
||||
using file = openFile("data.txt");
|
||||
processFile(file);
|
||||
// file.close() called automatically via Symbol.dispose
|
||||
```
|
||||
|
||||
**Why:** The `using` keyword (TypeScript 5.2+) provides deterministic resource cleanup via the
|
||||
Disposable protocol, similar to Python's `with` or C#'s `using`.
|
||||
|
||||
## Patterns
|
||||
|
||||
- Enable `strict: true` and `noUncheckedIndexedAccess: true` in every project
|
||||
- Use `satisfies` for type validation without widening
|
||||
- Use discriminated unions with a `type` or `kind` field for state modeling
|
||||
- Use `as const` for configuration objects and route maps
|
||||
- Use branded types for domain-specific IDs
|
||||
- Use `import type` for all type-only imports
|
||||
- Use exhaustive `switch` with `never` default for union handling
|
||||
|
||||
## Anti-Patterns
|
||||
|
||||
- NEVER use `any` - use `unknown` and narrow with type guards
|
||||
- NEVER use `as` for type assertions unless you genuinely know more than the compiler
|
||||
- NEVER use optional fields to model mutually exclusive states - use discriminated unions
|
||||
- NEVER use `// @ts-ignore` or `// @ts-expect-error` without a comment explaining why
|
||||
- NEVER use `enum` - use `as const` objects or union types instead
|
||||
- NEVER use `Function` type - use specific function signatures
|
||||
- NEVER disable strict mode for convenience
|
||||
@@ -0,0 +1,17 @@
|
||||
# Turbopack Dev Server Hang — @vidstack/react + Barrel Circular Import
|
||||
|
||||
**Applies when:** Next.js dev server hangs (290%+ CPU, 1GB+ RAM, no HTTP responses), or Turbopack enters infinite recompilation
|
||||
|
||||
Three contributing factors found:
|
||||
|
||||
1. **Barrel self-import in features/project**: `SubtitleRevisionStep.tsx` imports `TranscriptionEditor` from the barrel `@features/project` which re-exports `SubtitleRevisionStep` itself, creating a circular module evaluation chain. Fix: use direct subpath import.
|
||||
|
||||
2. **FSD violation features->widgets**: `SubtitleRevisionStep` imports `TimelinePanel` from `@widgets/`, violating FSD layer direction. Not a direct cause of hang but exacerbates module graph complexity.
|
||||
|
||||
3. **@vidstack/react internal dynamic imports**: The library uses 14+ dynamic `import()` calls internally. Combined with Turbopack's inability to create shared chunks between async chunks in dev mode (GitHub issue vercel/next.js#85119), this can cause pathological module duplication during HMR.
|
||||
|
||||
**Reproduction**: Issue is intermittent — most reliably triggered when editing files that import from `@vidstack/react` while the browser has the project wizard page open. Fresh server starts work fine.
|
||||
|
||||
**Quick fix**: Change `SubtitleRevisionStep.tsx` line 23 from `import { TranscriptionEditor } from "@features/project"` to `import { TranscriptionEditor } from "@features/project/TranscriptionEditor"`.
|
||||
|
||||
**Long-term**: Consider upgrading to Next.js 16.2+ which includes 200+ Turbopack fixes.
|
||||
@@ -0,0 +1,9 @@
|
||||
# oven/bun Base Image Has Existing Non-Root User
|
||||
|
||||
**Applies when:** adding non-root user to any Dockerfile that uses `oven/bun` as base image (Remotion service, or future Bun-based services).
|
||||
|
||||
- `oven/bun:1.3.10` ships with a `bun` user (UID 1000) and `bun` group (GID 1000).
|
||||
- Home directory is `/home/bun`, shell is `/bin/sh`.
|
||||
- Do NOT create a new `app` user with `groupadd`/`useradd` -- GID 1000 collision causes `groupadd: GID '1000' already exists` build failure.
|
||||
- Instead: `RUN chown -R bun:bun /app` then `USER bun`.
|
||||
- Verified: container runs as `uid=1000(bun) gid=1000(bun)`, `/app/out` is writable.
|
||||
@@ -0,0 +1,9 @@
|
||||
# cap_drop: ALL Breaks redis-alpine Startup
|
||||
|
||||
**Applies when:** adding Linux capability restrictions to Docker Compose services, especially Redis or any image that switches users at startup.
|
||||
|
||||
- `redis:7-alpine` entrypoint calls `gosu redis` to drop from root to the `redis` user.
|
||||
- `gosu` requires `SETUID` and `SETGID` capabilities to switch users.
|
||||
- `cap_drop: ALL` without `cap_add: [SETUID, SETGID]` prevents the user switch, causing immediate container exit.
|
||||
- The container logs show no error -- it just exits silently with code 1.
|
||||
- Decision (2026-03-24): removed all cap_drop/cap_add from both compose files. For a dev-only local stack, the complexity and debugging cost outweigh the security benefit. Revisit for production deployment with proper per-service capability analysis.
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user