Compare commits
383 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 74b67101ae | |||
| 3279f40541 | |||
| 62331e5c7b | |||
| d9c3d8ae1d | |||
| c34812841e | |||
| 28e2c58366 | |||
| a9e3ed6a22 | |||
| 48aabc9a7d | |||
| b72b39ad7e | |||
| f04989e973 | |||
| e5bcd7a224 | |||
| fbf31d706c | |||
| b782329ae2 | |||
| 65e20638ff | |||
| 19048f6ead | |||
| b29a5f1748 | |||
| 8783d949ba | |||
| bee6bd1cbd | |||
| bdea15ace9 | |||
| 72acd2ca94 | |||
| ba5f389dbe | |||
| aaa5ee69d2 | |||
| fb671d5790 | |||
| e32bfd1cb2 | |||
| 50a1a90e6a | |||
| 2406b5b617 | |||
| 913d645d89 | |||
| c7dd925a34 | |||
| c289d3690f | |||
| 8224c68f66 | |||
| 6571fc022d | |||
| 109c09a911 | |||
| 90d7fe578f | |||
| 82f948cdd9 | |||
| 25d149e9ef | |||
| 8d757ba18d | |||
| 4f1c9fe65c | |||
| 78e3f96e3a | |||
| 0c377b7cb8 | |||
| c2db365729 | |||
| 7e21097175 | |||
| 0a36e39156 | |||
| d178fa4510 | |||
| 8ca4d443c4 | |||
| a9075606ad | |||
| 05da1e1a75 | |||
| b5e0456786 | |||
| 218603ff9f | |||
| 6f19d08a08 | |||
| 5079180a31 | |||
| b291e30b13 | |||
| 9428f52f7d | |||
| 0be4e5b9e6 | |||
| 5f8b1442c9 | |||
| b6c0c64dfa | |||
| 548ca9cd46 | |||
| 5d1dc7716f | |||
| e9795e1667 | |||
| 1dd39a6973 | |||
| de3b805ea0 | |||
| 452bbc3b7d | |||
| ae50e1d995 | |||
| 7fd898a23a | |||
| b7527a012a | |||
| 5349295df8 | |||
| 38a4f63269 | |||
| a6eae611af | |||
| 6dbe57c625 | |||
| f567f4f4a9 | |||
| b36585b927 | |||
| 7c2a0474cd | |||
| 8d4903bdff | |||
| 7eb654b6a5 | |||
| 403e01b28a | |||
| da5fa76c04 | |||
| b2fa4d2fbc | |||
| c0bbfa5b09 | |||
| f6e59e864a | |||
| ee669f94ab | |||
| fa79482682 | |||
| 69cd2e6394 | |||
| b363b3dd7d | |||
| 23fc28805b | |||
| ba9e22381b | |||
| ec2f82db37 | |||
| 8f47bf93af | |||
| 0bb8f93e94 | |||
| 23108c342b | |||
| 43c11928fa | |||
| 4b01faad42 | |||
| 10beac128f | |||
| 3f4dc0290e | |||
| 38cb884b77 | |||
| e659fccfad | |||
| 21e232f042 | |||
| e4aa62e6e4 | |||
| 36daf13822 | |||
| 55833142bd | |||
| 350e02c0f0 | |||
| f2d150bb02 | |||
| fff1259704 | |||
| 9470f357ec | |||
| c1b8d67849 | |||
| 52c3cdfc60 | |||
| 9156cf9cd9 | |||
| 38fa71b44b | |||
| ce406767be | |||
| 8a5ac39cc5 | |||
| 906db36c81 | |||
| 208f2095bf | |||
| e6a8a76d32 | |||
| 41eda86917 | |||
| ffd3170261 | |||
| 2425598c6a | |||
| e413bb5f38 | |||
| 93432c5968 | |||
| a0c10de673 | |||
| ffc4940508 | |||
| 72241bffd4 | |||
| b6d3f80f03 | |||
| 4c93a1bdfa | |||
| 85c0ff01e8 | |||
| a9129f4a3c | |||
| 84ed412899 | |||
| e5138360d8 | |||
| e6441aae6d | |||
| a611919bcb | |||
| c0cf028c55 | |||
| d3142586f7 | |||
| 8e8e71bd6b | |||
| 1a58a05ce4 | |||
| 8c70945a40 | |||
| 515bbe9b8e | |||
| 0e6b86b3a0 | |||
| b2bcfebeea | |||
| cc81040641 | |||
| 84102b4b00 | |||
| 3a565676e3 | |||
| 8f1df0c008 | |||
| e6c58bc2b7 | |||
| 217bdde7d8 | |||
| 299bd25c69 | |||
| deb3f9ff67 | |||
| f9418857bd | |||
| 6294502641 | |||
| 336147166c | |||
| 9406d8c2cb | |||
| 99ceba5363 | |||
| 7dca0a1c81 | |||
| 8fc92801ce | |||
| 506cd12fba | |||
| 343c41a862 | |||
| a3f0658cf0 | |||
| e33d695ca9 | |||
| cfe0644962 | |||
| bc64464e20 | |||
| 3d4ae46e30 | |||
| 0ff360e7d6 | |||
| 0ad5f54ed3 | |||
| 4a560a0f63 | |||
| 7aa22d096f | |||
| 9202051ff4 | |||
| 9e9748c6f8 | |||
| ec94a136d6 | |||
| cb961bdc2f | |||
| 45f740c36f | |||
| 993c8f73ed | |||
| a52518be28 | |||
| 4c22bbdc18 | |||
| 18cb7709de | |||
| c1bda7fa9c | |||
| b55dd91320 | |||
| 9c2f4664d6 | |||
| 2467088b2f | |||
| 53d59c3ab9 | |||
| e174aeef6a | |||
| f490539ee2 | |||
| 74b3826319 | |||
| 910d1c30a6 | |||
| c5f2dc94c9 | |||
| 4cd1955235 | |||
| 16809c4ab5 | |||
| 52e40fed54 | |||
| bd833e7590 | |||
| f26248f0df | |||
| 1fe1df486f | |||
| 6189ca7f9a | |||
| 9c5cdfff0d | |||
| 7423e5cfca | |||
| b9a4f5db57 | |||
| 5717f454e6 | |||
| efae7de938 | |||
| 1ea3c02471 | |||
| cece6ee89b | |||
| 02233e15fb | |||
| 9e0752cafc | |||
| f92f1affc6 | |||
| 9e0869b675 | |||
| b09b0a300e | |||
| 2fe71f39c7 | |||
| 77b08f33c2 | |||
| 919c872106 | |||
| 02c33e468d | |||
| c1a84b25a3 | |||
| c5251c1b3e | |||
| 675b277f17 | |||
| c673363848 | |||
| 44ca432508 | |||
| 9d0e663928 | |||
| 438ddfb46b | |||
| 13077a571f | |||
| 0482b6bbae | |||
| 171e46cf1b | |||
| 427e552ed7 | |||
| fa7a175260 | |||
| 39d2646cd8 | |||
| dccc3db755 | |||
| c452b14b2f | |||
| cad18fafc0 | |||
| 43160bf5e7 | |||
| d97131d081 | |||
| 4cf87b7811 | |||
| fe7eae890b | |||
| 174c11e792 | |||
| 463664f7ec | |||
| 59617b868f | |||
| 5795d8cadd | |||
| 9323f54ac6 | |||
| e733f13fde | |||
| 4a340617e6 | |||
| e1af2310f4 | |||
| 395c3fac2c | |||
| 26a402366d | |||
| 4290c8648b | |||
| 467cc1da3a | |||
| 5dad2fb876 | |||
| 3c78f377fc | |||
| b869f23b20 | |||
| 144ba39fdc | |||
| ebb544cbcb | |||
| 65be51094d | |||
| ecc45895d0 | |||
| 252a166978 | |||
| 49195f4206 | |||
| 0659964009 | |||
| 103a111191 | |||
| 1a45c685e7 | |||
| d6ae275bf3 | |||
| a51cf4e9b1 | |||
| 0867e2da0f | |||
| 779172f953 | |||
| c31bd974db | |||
| 81a72bbc1a | |||
| fb380ffcc6 | |||
| 15f3aecc9d | |||
| c2c198c636 | |||
| 75eed24552 | |||
| ad51d812d7 | |||
| 33f893f961 | |||
| 67631c995a | |||
| fb45213073 | |||
| e0671bd4c8 | |||
| 80e493e1ae | |||
| c19d3b1fd7 | |||
| d57c67eca6 | |||
| 4a1239b100 | |||
| cbe337baed | |||
| f6433e8f80 | |||
| a6aa2094e2 | |||
| a264284c05 | |||
| 0e898be77c | |||
| bd6a974e5c | |||
| 5356a580f2 | |||
| 90218e876e | |||
| 735dc4bbd5 | |||
| 3113617d26 | |||
| e5fad91210 | |||
| 763a5fcd86 | |||
| ba36d89cef | |||
| b5ecbbb748 | |||
| 386c6bfe16 | |||
| a792fdc0b1 | |||
| 4358f7b767 | |||
| 658b245baf | |||
| b6dcd6fac7 | |||
| 953f9032b9 | |||
| 60652fbcd0 | |||
| e8d5cf5c7a | |||
| 4b34f51d96 | |||
| 14a88a78ed | |||
| d6a8992d04 | |||
| 63ddc1457b | |||
| ca6a90ec63 | |||
| f7a2790285 | |||
| e62a591c24 | |||
| 8e5089b8db | |||
| f9cbb7dfd4 | |||
| 4f5625f7b4 | |||
| fa2c8de385 | |||
| 68fcbd1670 | |||
| c5a9398607 | |||
| 6886bf7e06 | |||
| d1871a1bb2 | |||
| 05407600d6 | |||
| ba7e280b82 | |||
| 0857376da5 | |||
| d39e1fb1c5 | |||
| 9867d26bdd | |||
| e5f6d70b7c | |||
| 2b363a91a9 | |||
| c79fba28d1 | |||
| 66b841697d | |||
| 98ee8d88f7 | |||
| b6a1328be4 | |||
| 4f6636b9eb | |||
| 1a33e35fe4 | |||
| 17a76f9db0 | |||
| 4cd50e54c1 | |||
| 215b1a85d0 | |||
| deb73cdcce | |||
| d4fe4c0aab | |||
| dd862e90bb | |||
| 33f02b5719 | |||
| ed8ea0861e | |||
| 1b445927dd | |||
| b65e0f8bd6 | |||
| 9d30a04cdf | |||
| 134237fc5e | |||
| 1a933fc3a2 | |||
| 63087901b9 | |||
| bd56f2aa04 | |||
| de86c861d8 | |||
| af3b8a2a6b | |||
| 6b40256ee3 | |||
| d8f3f083c7 | |||
| 47d3d786ca | |||
| 1c755b4bd5 | |||
| 0cece2b194 | |||
| 840fc610f0 | |||
| 6e55fe9f34 | |||
| c8c7351f9e | |||
| 9bf2aa2c48 | |||
| 1620b8e4c4 | |||
| f798bd3d8b | |||
| 65850f158c | |||
| 8f5991e65f | |||
| 5492e1df35 | |||
| 93fbd8768b | |||
| 246f079905 | |||
| b25285fcc2 | |||
| 7a2b31d328 | |||
| a4ac847f0d | |||
| 6b632b5502 | |||
| 560a77ca52 | |||
| 86e1345684 | |||
| b91de0e442 | |||
| 62e47aac4c | |||
| 43fb92ac82 | |||
| de5ecb570f | |||
| 014c851a03 | |||
| eae07b1d3b | |||
| df06736722 | |||
| 25b90a0993 | |||
| ad1b58bf53 | |||
| 259118e48b | |||
| 145ac6bb12 | |||
| 7b581ff917 | |||
| 62423f8156 | |||
| 5fd539445e | |||
| 7c756cccef | |||
| 786826b434 | |||
| 56f41999b5 | |||
| 7423cf89ab | |||
| 8c6ee20b30 | |||
| 17ffa1acc0 | |||
| cec95c9f0a | |||
| eaf3d46e24 | |||
| c30badabbf | |||
| 40cdecc820 | |||
| 3c1088b6d6 | |||
| ac9a4c8f48 | |||
| b79ab2ee3f | |||
| ceef11bca6 |
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,127 @@
|
||||
# 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).
|
||||
@@ -0,0 +1,148 @@
|
||||
---
|
||||
name: vercel-react-best-practices
|
||||
description: React and Next.js performance optimization guidelines from Vercel Engineering. This skill should be used when writing, reviewing, or refactoring React/Next.js code to ensure optimal performance patterns. Triggers on tasks involving React components, Next.js pages, data fetching, bundle optimization, or performance improvements.
|
||||
license: MIT
|
||||
metadata:
|
||||
author: vercel
|
||||
version: "1.0.0"
|
||||
---
|
||||
|
||||
# Vercel React Best Practices
|
||||
|
||||
Comprehensive performance optimization guide for React and Next.js applications, maintained by Vercel. Contains 67 rules across 8 categories, prioritized by impact to guide automated refactoring and code generation.
|
||||
|
||||
## When to Apply
|
||||
|
||||
Reference these guidelines when:
|
||||
|
||||
- Writing new React components or Next.js pages
|
||||
- Implementing data fetching (client or server-side)
|
||||
- Reviewing code for performance issues
|
||||
- Refactoring existing React/Next.js code
|
||||
- Optimizing bundle size or load times
|
||||
|
||||
## Rule Categories by Priority
|
||||
|
||||
| Priority | Category | Impact | Prefix |
|
||||
| -------- | ------------------------- | ----------- | ------------ |
|
||||
| 1 | Eliminating Waterfalls | CRITICAL | `async-` |
|
||||
| 2 | Bundle Size Optimization | CRITICAL | `bundle-` |
|
||||
| 3 | Server-Side Performance | HIGH | `server-` |
|
||||
| 4 | Client-Side Data Fetching | MEDIUM-HIGH | `client-` |
|
||||
| 5 | Re-render Optimization | MEDIUM | `rerender-` |
|
||||
| 6 | Rendering Performance | MEDIUM | `rendering-` |
|
||||
| 7 | JavaScript Performance | LOW-MEDIUM | `js-` |
|
||||
| 8 | Advanced Patterns | LOW | `advanced-` |
|
||||
|
||||
## Quick Reference
|
||||
|
||||
### 1. Eliminating Waterfalls (CRITICAL)
|
||||
|
||||
- `async-cheap-condition-before-await` - Check cheap sync conditions before awaiting flags or remote values
|
||||
- `async-defer-await` - Move await into branches where actually used
|
||||
- `async-parallel` - Use Promise.all() for independent operations
|
||||
- `async-dependencies` - Use better-all for partial dependencies
|
||||
- `async-api-routes` - Start promises early, await late in API routes
|
||||
- `async-suspense-boundaries` - Use Suspense to stream content
|
||||
|
||||
### 2. Bundle Size Optimization (CRITICAL)
|
||||
|
||||
- `bundle-barrel-imports` - Import directly, avoid barrel files
|
||||
- `bundle-dynamic-imports` - Use next/dynamic for heavy components
|
||||
- `bundle-defer-third-party` - Load analytics/logging after hydration
|
||||
- `bundle-conditional` - Load modules only when feature is activated
|
||||
- `bundle-preload` - Preload on hover/focus for perceived speed
|
||||
|
||||
### 3. Server-Side Performance (HIGH)
|
||||
|
||||
- `server-auth-actions` - Authenticate server actions like API routes
|
||||
- `server-cache-react` - Use React.cache() for per-request deduplication
|
||||
- `server-cache-lru` - Use LRU cache for cross-request caching
|
||||
- `server-dedup-props` - Avoid duplicate serialization in RSC props
|
||||
- `server-hoist-static-io` - Hoist static I/O (fonts, logos) to module level
|
||||
- `server-serialization` - Minimize data passed to client components
|
||||
- `server-parallel-fetching` - Restructure components to parallelize fetches
|
||||
- `server-parallel-nested-fetching` - Chain nested fetches per item in Promise.all
|
||||
- `server-after-nonblocking` - Use after() for non-blocking operations
|
||||
|
||||
### 4. Client-Side Data Fetching (MEDIUM-HIGH)
|
||||
|
||||
- `client-swr-dedup` - Use SWR for automatic request deduplication
|
||||
- `client-event-listeners` - Deduplicate global event listeners
|
||||
- `client-passive-event-listeners` - Use passive listeners for scroll
|
||||
- `client-localstorage-schema` - Version and minimize localStorage data
|
||||
|
||||
### 5. Re-render Optimization (MEDIUM)
|
||||
|
||||
- `rerender-defer-reads` - Don't subscribe to state only used in callbacks
|
||||
- `rerender-memo` - Extract expensive work into memoized components
|
||||
- `rerender-memo-with-default-value` - Hoist default non-primitive props
|
||||
- `rerender-dependencies` - Use primitive dependencies in effects
|
||||
- `rerender-derived-state` - Subscribe to derived booleans, not raw values
|
||||
- `rerender-derived-state-no-effect` - Derive state during render, not effects
|
||||
- `rerender-functional-setstate` - Use functional setState for stable callbacks
|
||||
- `rerender-lazy-state-init` - Pass function to useState for expensive values
|
||||
- `rerender-simple-expression-in-memo` - Avoid memo for simple primitives
|
||||
- `rerender-split-combined-hooks` - Split hooks with independent dependencies
|
||||
- `rerender-move-effect-to-event` - Put interaction logic in event handlers
|
||||
- `rerender-transitions` - Use startTransition for non-urgent updates
|
||||
- `rerender-use-deferred-value` - Defer expensive renders to keep input responsive
|
||||
- `rerender-use-ref-transient-values` - Use refs for transient frequent values
|
||||
- `rerender-no-inline-components` - Don't define components inside components
|
||||
|
||||
### 6. Rendering Performance (MEDIUM)
|
||||
|
||||
- `rendering-animate-svg-wrapper` - Animate div wrapper, not SVG element
|
||||
- `rendering-content-visibility` - Use content-visibility for long lists
|
||||
- `rendering-hoist-jsx` - Extract static JSX outside components
|
||||
- `rendering-svg-precision` - Reduce SVG coordinate precision
|
||||
- `rendering-hydration-no-flicker` - Use inline script for client-only data
|
||||
- `rendering-hydration-suppress-warning` - Suppress expected mismatches
|
||||
- `rendering-activity` - Use Activity component for show/hide
|
||||
- `rendering-conditional-render` - Use ternary, not && for conditionals
|
||||
- `rendering-usetransition-loading` - Prefer useTransition for loading state
|
||||
- `rendering-resource-hints` - Use React DOM resource hints for preloading
|
||||
- `rendering-script-defer-async` - Use defer or async on script tags
|
||||
|
||||
### 7. JavaScript Performance (LOW-MEDIUM)
|
||||
|
||||
- `js-batch-dom-css` - Group CSS changes via classes or cssText
|
||||
- `js-index-maps` - Build Map for repeated lookups
|
||||
- `js-cache-property-access` - Cache object properties in loops
|
||||
- `js-cache-function-results` - Cache function results in module-level Map
|
||||
- `js-cache-storage` - Cache localStorage/sessionStorage reads
|
||||
- `js-combine-iterations` - Combine multiple filter/map into one loop
|
||||
- `js-length-check-first` - Check array length before expensive comparison
|
||||
- `js-early-exit` - Return early from functions
|
||||
- `js-hoist-regexp` - Hoist RegExp creation outside loops
|
||||
- `js-min-max-loop` - Use loop for min/max instead of sort
|
||||
- `js-set-map-lookups` - Use Set/Map for O(1) lookups
|
||||
- `js-tosorted-immutable` - Use toSorted() for immutability
|
||||
- `js-flatmap-filter` - Use flatMap to map and filter in one pass
|
||||
- `js-request-idle-callback` - Defer non-critical work to browser idle time
|
||||
|
||||
### 8. Advanced Patterns (LOW)
|
||||
|
||||
- `advanced-event-handler-refs` - Store event handlers in refs
|
||||
- `advanced-init-once` - Initialize app once per app load
|
||||
- `advanced-use-latest` - useLatest for stable callback refs
|
||||
|
||||
## How to Use
|
||||
|
||||
Read individual rule files for detailed explanations and code examples:
|
||||
|
||||
```
|
||||
rules/async-parallel.md
|
||||
rules/bundle-barrel-imports.md
|
||||
```
|
||||
|
||||
Each rule file contains:
|
||||
|
||||
- Brief explanation of why it matters
|
||||
- Incorrect code example with explanation
|
||||
- Correct code example with explanation
|
||||
- Additional context and references
|
||||
|
||||
## Full Compiled Document
|
||||
|
||||
For the complete guide with all rules expanded: `AGENTS.md`
|
||||
@@ -0,0 +1,46 @@
|
||||
# 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.
|
||||
@@ -0,0 +1,28 @@
|
||||
---
|
||||
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)
|
||||
@@ -0,0 +1,55 @@
|
||||
---
|
||||
title: Store Event Handlers in Refs
|
||||
impact: LOW
|
||||
impactDescription: stable subscriptions
|
||||
tags: advanced, hooks, refs, event-handlers, optimization
|
||||
---
|
||||
|
||||
## Store Event Handlers in Refs
|
||||
|
||||
Store callbacks in refs when used in effects that shouldn't re-subscribe on callback changes.
|
||||
|
||||
**Incorrect (re-subscribes on every render):**
|
||||
|
||||
```tsx
|
||||
function useWindowEvent(event: string, handler: (e) => void) {
|
||||
useEffect(() => {
|
||||
window.addEventListener(event, handler);
|
||||
return () => window.removeEventListener(event, handler);
|
||||
}, [event, handler]);
|
||||
}
|
||||
```
|
||||
|
||||
**Correct (stable subscription):**
|
||||
|
||||
```tsx
|
||||
function useWindowEvent(event: string, handler: (e) => void) {
|
||||
const handlerRef = useRef(handler);
|
||||
useEffect(() => {
|
||||
handlerRef.current = handler;
|
||||
}, [handler]);
|
||||
|
||||
useEffect(() => {
|
||||
const listener = (e) => handlerRef.current(e);
|
||||
window.addEventListener(event, listener);
|
||||
return () => window.removeEventListener(event, listener);
|
||||
}, [event]);
|
||||
}
|
||||
```
|
||||
|
||||
**Alternative: use `useEffectEvent` if you're on latest React:**
|
||||
|
||||
```tsx
|
||||
import { useEffectEvent } from "react";
|
||||
|
||||
function useWindowEvent(event: string, handler: (e) => void) {
|
||||
const onEvent = useEffectEvent(handler);
|
||||
|
||||
useEffect(() => {
|
||||
window.addEventListener(event, onEvent);
|
||||
return () => window.removeEventListener(event, onEvent);
|
||||
}, [event]);
|
||||
}
|
||||
```
|
||||
|
||||
`useEffectEvent` provides a cleaner API for the same pattern: it creates a stable function reference that always calls the latest version of the handler.
|
||||
@@ -0,0 +1,42 @@
|
||||
---
|
||||
title: Initialize App Once, Not Per Mount
|
||||
impact: LOW-MEDIUM
|
||||
impactDescription: avoids duplicate init in development
|
||||
tags: initialization, useEffect, app-startup, side-effects
|
||||
---
|
||||
|
||||
## Initialize App Once, Not Per Mount
|
||||
|
||||
Do not put app-wide initialization that must run once per app load inside `useEffect([])` of a component. Components can remount and effects will re-run. Use a module-level guard or top-level init in the entry module instead.
|
||||
|
||||
**Incorrect (runs twice in dev, re-runs on remount):**
|
||||
|
||||
```tsx
|
||||
function Comp() {
|
||||
useEffect(() => {
|
||||
loadFromStorage();
|
||||
checkAuthToken();
|
||||
}, []);
|
||||
|
||||
// ...
|
||||
}
|
||||
```
|
||||
|
||||
**Correct (once per app load):**
|
||||
|
||||
```tsx
|
||||
let didInit = false;
|
||||
|
||||
function Comp() {
|
||||
useEffect(() => {
|
||||
if (didInit) return;
|
||||
didInit = true;
|
||||
loadFromStorage();
|
||||
checkAuthToken();
|
||||
}, []);
|
||||
|
||||
// ...
|
||||
}
|
||||
```
|
||||
|
||||
Reference: [Initializing the application](https://react.dev/learn/you-might-not-need-an-effect#initializing-the-application)
|
||||
@@ -0,0 +1,39 @@
|
||||
---
|
||||
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]);
|
||||
}
|
||||
```
|
||||
@@ -0,0 +1,38 @@
|
||||
---
|
||||
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
@@ -0,0 +1,37 @@
|
||||
---
|
||||
title: Check Cheap Conditions Before Async Flags
|
||||
impact: HIGH
|
||||
impactDescription: avoids unnecessary async work when a synchronous guard already fails
|
||||
tags: async, await, feature-flags, short-circuit, conditional
|
||||
---
|
||||
|
||||
## Check Cheap Conditions Before Async Flags
|
||||
|
||||
When a branch uses `await` for a flag or remote value and also requires a **cheap synchronous** condition (local props, request metadata, already-loaded state), evaluate the cheap condition **first**. Otherwise you pay for the async call even when the compound condition can never be true.
|
||||
|
||||
This is a specialization of [Defer Await Until Needed](./async-defer-await.md) for `flag && cheapCondition` style checks.
|
||||
|
||||
**Incorrect:**
|
||||
|
||||
```typescript
|
||||
const someFlag = await getFlag();
|
||||
|
||||
if (someFlag && someCondition) {
|
||||
// ...
|
||||
}
|
||||
```
|
||||
|
||||
**Correct:**
|
||||
|
||||
```typescript
|
||||
if (someCondition) {
|
||||
const someFlag = await getFlag();
|
||||
if (someFlag) {
|
||||
// ...
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
This matters when `getFlag` hits the network, a feature-flag service, or `React.cache` / DB work: skipping it when `someCondition` is false removes that cost on the cold path.
|
||||
|
||||
Keep the original order if `someCondition` is expensive, depends on the flag, or you must run side effects in a fixed order.
|
||||
@@ -0,0 +1,82 @@
|
||||
---
|
||||
title: Defer Await Until Needed
|
||||
impact: HIGH
|
||||
impactDescription: avoids blocking unused code paths
|
||||
tags: async, await, conditional, optimization
|
||||
---
|
||||
|
||||
## Defer Await Until Needed
|
||||
|
||||
Move `await` operations into the branches where they're actually used to avoid blocking code paths that don't need them.
|
||||
|
||||
**Incorrect (blocks both branches):**
|
||||
|
||||
```typescript
|
||||
async function handleRequest(userId: string, skipProcessing: boolean) {
|
||||
const userData = await fetchUserData(userId);
|
||||
|
||||
if (skipProcessing) {
|
||||
// Returns immediately but still waited for userData
|
||||
return { skipped: true };
|
||||
}
|
||||
|
||||
// Only this branch uses userData
|
||||
return processUserData(userData);
|
||||
}
|
||||
```
|
||||
|
||||
**Correct (only blocks when needed):**
|
||||
|
||||
```typescript
|
||||
async function handleRequest(userId: string, skipProcessing: boolean) {
|
||||
if (skipProcessing) {
|
||||
// Returns immediately without waiting
|
||||
return { skipped: true };
|
||||
}
|
||||
|
||||
// Fetch only when needed
|
||||
const userData = await fetchUserData(userId);
|
||||
return processUserData(userData);
|
||||
}
|
||||
```
|
||||
|
||||
**Another example (early return optimization):**
|
||||
|
||||
```typescript
|
||||
// Incorrect: always fetches permissions
|
||||
async function updateResource(resourceId: string, userId: string) {
|
||||
const permissions = await fetchPermissions(userId);
|
||||
const resource = await getResource(resourceId);
|
||||
|
||||
if (!resource) {
|
||||
return { error: "Not found" };
|
||||
}
|
||||
|
||||
if (!permissions.canEdit) {
|
||||
return { error: "Forbidden" };
|
||||
}
|
||||
|
||||
return await updateResourceData(resource, permissions);
|
||||
}
|
||||
|
||||
// Correct: fetches only when needed
|
||||
async function updateResource(resourceId: string, userId: string) {
|
||||
const resource = await getResource(resourceId);
|
||||
|
||||
if (!resource) {
|
||||
return { error: "Not found" };
|
||||
}
|
||||
|
||||
const permissions = await fetchPermissions(userId);
|
||||
|
||||
if (!permissions.canEdit) {
|
||||
return { error: "Forbidden" };
|
||||
}
|
||||
|
||||
return await updateResourceData(resource, permissions);
|
||||
}
|
||||
```
|
||||
|
||||
This optimization is especially valuable when the skipped branch is frequently taken, or when the deferred operation is expensive.
|
||||
|
||||
For `await getFlag()` combined with a cheap synchronous guard (`flag && someCondition`), see [Check Cheap Conditions Before Async Flags](./async-cheap-condition-before-await.md).
|
||||
@@ -0,0 +1,52 @@
|
||||
---
|
||||
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)
|
||||
@@ -0,0 +1,28 @@
|
||||
---
|
||||
title: Promise.all() for Independent Operations
|
||||
impact: CRITICAL
|
||||
impactDescription: 2-10× improvement
|
||||
tags: async, parallelization, promises, waterfalls
|
||||
---
|
||||
|
||||
## Promise.all() for Independent Operations
|
||||
|
||||
When async operations have no interdependencies, execute them concurrently using `Promise.all()`.
|
||||
|
||||
**Incorrect (sequential execution, 3 round trips):**
|
||||
|
||||
```typescript
|
||||
const user = await fetchUser();
|
||||
const posts = await fetchPosts();
|
||||
const comments = await fetchComments();
|
||||
```
|
||||
|
||||
**Correct (parallel execution, 1 round trip):**
|
||||
|
||||
```typescript
|
||||
const [user, posts, comments] = await Promise.all([
|
||||
fetchUser(),
|
||||
fetchPosts(),
|
||||
fetchComments(),
|
||||
]);
|
||||
```
|
||||
@@ -0,0 +1,99 @@
|
||||
---
|
||||
title: Strategic Suspense Boundaries
|
||||
impact: HIGH
|
||||
impactDescription: faster initial paint
|
||||
tags: async, suspense, streaming, layout-shift
|
||||
---
|
||||
|
||||
## Strategic Suspense Boundaries
|
||||
|
||||
Instead of awaiting data in async components before returning JSX, use Suspense boundaries to show the wrapper UI faster while data loads.
|
||||
|
||||
**Incorrect (wrapper blocked by data fetching):**
|
||||
|
||||
```tsx
|
||||
async function Page() {
|
||||
const data = await fetchData(); // Blocks entire page
|
||||
|
||||
return (
|
||||
<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.
|
||||
@@ -0,0 +1,60 @@
|
||||
---
|
||||
title: Avoid Barrel File Imports
|
||||
impact: CRITICAL
|
||||
impactDescription: 200-800ms import cost, slow builds
|
||||
tags: bundle, imports, tree-shaking, barrel-files, performance
|
||||
---
|
||||
|
||||
## Avoid Barrel File Imports
|
||||
|
||||
Import directly from source files instead of barrel files to avoid loading thousands of unused modules. **Barrel files** are entry points that re-export multiple modules (e.g., `index.js` that does `export * from './module'`).
|
||||
|
||||
Popular icon and component libraries can have **up to 10,000 re-exports** in their entry file. For many React packages, **it takes 200-800ms just to import them**, affecting both development speed and production cold starts.
|
||||
|
||||
**Why tree-shaking doesn't help:** When a library is marked as external (not bundled), the bundler can't optimize it. If you bundle it to enable tree-shaking, builds become substantially slower analyzing the entire module graph.
|
||||
|
||||
**Incorrect (imports entire library):**
|
||||
|
||||
```tsx
|
||||
import { Check, X, Menu } from "lucide-react";
|
||||
// Loads 1,583 modules, takes ~2.8s extra in dev
|
||||
// Runtime cost: 200-800ms on every cold start
|
||||
|
||||
import { Button, TextField } from "@mui/material";
|
||||
// Loads 2,225 modules, takes ~4.2s extra in dev
|
||||
```
|
||||
|
||||
**Correct - Next.js 13.5+ (recommended):**
|
||||
|
||||
```js
|
||||
// next.config.js - automatically optimizes barrel imports at build time
|
||||
module.exports = {
|
||||
experimental: {
|
||||
optimizePackageImports: ["lucide-react", "@mui/material"],
|
||||
},
|
||||
};
|
||||
```
|
||||
|
||||
```tsx
|
||||
// Keep the standard imports - Next.js transforms them to direct imports
|
||||
import { Check, X, Menu } from "lucide-react";
|
||||
// Full TypeScript support, no manual path wrangling
|
||||
```
|
||||
|
||||
This is the recommended approach because it preserves TypeScript type safety and editor autocompletion while still eliminating the barrel import cost.
|
||||
|
||||
**Correct - Direct imports (non-Next.js projects):**
|
||||
|
||||
```tsx
|
||||
import Button from "@mui/material/Button";
|
||||
import TextField from "@mui/material/TextField";
|
||||
// Loads only what you use
|
||||
```
|
||||
|
||||
> **TypeScript warning:** Some libraries (notably `lucide-react`) don't ship `.d.ts` files for their deep import paths. Importing from `lucide-react/dist/esm/icons/check` resolves to an implicit `any` type, causing errors under `strict` or `noImplicitAny`. Prefer `optimizePackageImports` when available, or verify the library exports types for its subpaths before using direct imports.
|
||||
|
||||
These optimizations provide 15-70% faster dev boot, 28% faster builds, 40% faster cold starts, and significantly faster HMR.
|
||||
|
||||
Libraries commonly affected: `lucide-react`, `@mui/material`, `@mui/icons-material`, `@tabler/icons-react`, `react-icons`, `@headlessui/react`, `@radix-ui/react-*`, `lodash`, `ramda`, `date-fns`, `rxjs`, `react-use`.
|
||||
|
||||
Reference: [How we optimized package imports in Next.js](https://vercel.com/blog/how-we-optimized-package-imports-in-next-js)
|
||||
@@ -0,0 +1,37 @@
|
||||
---
|
||||
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.
|
||||
@@ -0,0 +1,49 @@
|
||||
---
|
||||
title: Defer Non-Critical Third-Party Libraries
|
||||
impact: MEDIUM
|
||||
impactDescription: loads after hydration
|
||||
tags: bundle, third-party, analytics, defer
|
||||
---
|
||||
|
||||
## Defer Non-Critical Third-Party Libraries
|
||||
|
||||
Analytics, logging, and error tracking don't block user interaction. Load them after hydration.
|
||||
|
||||
**Incorrect (blocks initial bundle):**
|
||||
|
||||
```tsx
|
||||
import { Analytics } from "@vercel/analytics/react";
|
||||
|
||||
export default function RootLayout({ children }) {
|
||||
return (
|
||||
<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>
|
||||
);
|
||||
}
|
||||
```
|
||||
@@ -0,0 +1,35 @@
|
||||
---
|
||||
title: Dynamic Imports for Heavy Components
|
||||
impact: CRITICAL
|
||||
impactDescription: directly affects TTI and LCP
|
||||
tags: bundle, dynamic-import, code-splitting, next-dynamic
|
||||
---
|
||||
|
||||
## Dynamic Imports for Heavy Components
|
||||
|
||||
Use `next/dynamic` to lazy-load large components not needed on initial render.
|
||||
|
||||
**Incorrect (Monaco bundles with main chunk ~300KB):**
|
||||
|
||||
```tsx
|
||||
import { MonacoEditor } from "./monaco-editor";
|
||||
|
||||
function CodePanel({ code }: { code: string }) {
|
||||
return <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} />;
|
||||
}
|
||||
```
|
||||
@@ -0,0 +1,46 @@
|
||||
---
|
||||
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.
|
||||
@@ -0,0 +1,78 @@
|
||||
---
|
||||
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", () => {
|
||||
/* ... */
|
||||
});
|
||||
// ...
|
||||
}
|
||||
```
|
||||
@@ -0,0 +1,77 @@
|
||||
---
|
||||
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.
|
||||
@@ -0,0 +1,48 @@
|
||||
---
|
||||
title: Use Passive Event Listeners for Scrolling Performance
|
||||
impact: MEDIUM
|
||||
impactDescription: eliminates scroll delay caused by event listeners
|
||||
tags: client, event-listeners, scrolling, performance, touch, wheel
|
||||
---
|
||||
|
||||
## Use Passive Event Listeners for Scrolling Performance
|
||||
|
||||
Add `{ passive: true }` to touch and wheel event listeners to enable immediate scrolling. Browsers normally wait for listeners to finish to check if `preventDefault()` is called, causing scroll delay.
|
||||
|
||||
**Incorrect:**
|
||||
|
||||
```typescript
|
||||
useEffect(() => {
|
||||
const handleTouch = (e: TouchEvent) => console.log(e.touches[0].clientX);
|
||||
const handleWheel = (e: WheelEvent) => console.log(e.deltaY);
|
||||
|
||||
document.addEventListener("touchstart", handleTouch);
|
||||
document.addEventListener("wheel", handleWheel);
|
||||
|
||||
return () => {
|
||||
document.removeEventListener("touchstart", handleTouch);
|
||||
document.removeEventListener("wheel", handleWheel);
|
||||
};
|
||||
}, []);
|
||||
```
|
||||
|
||||
**Correct:**
|
||||
|
||||
```typescript
|
||||
useEffect(() => {
|
||||
const handleTouch = (e: TouchEvent) => console.log(e.touches[0].clientX);
|
||||
const handleWheel = (e: WheelEvent) => console.log(e.deltaY);
|
||||
|
||||
document.addEventListener("touchstart", handleTouch, { passive: true });
|
||||
document.addEventListener("wheel", handleWheel, { passive: true });
|
||||
|
||||
return () => {
|
||||
document.removeEventListener("touchstart", handleTouch);
|
||||
document.removeEventListener("wheel", handleWheel);
|
||||
};
|
||||
}, []);
|
||||
```
|
||||
|
||||
**Use passive when:** tracking/analytics, logging, any listener that doesn't call `preventDefault()`.
|
||||
|
||||
**Don't use passive when:** implementing custom swipe gestures, custom zoom controls, or any listener that needs `preventDefault()`.
|
||||
@@ -0,0 +1,56 @@
|
||||
---
|
||||
title: Use SWR for Automatic Deduplication
|
||||
impact: MEDIUM-HIGH
|
||||
impactDescription: automatic deduplication
|
||||
tags: client, swr, deduplication, data-fetching
|
||||
---
|
||||
|
||||
## Use SWR for Automatic Deduplication
|
||||
|
||||
SWR enables request deduplication, caching, and revalidation across component instances.
|
||||
|
||||
**Incorrect (no deduplication, each instance fetches):**
|
||||
|
||||
```tsx
|
||||
function UserList() {
|
||||
const [users, setUsers] = useState([]);
|
||||
useEffect(() => {
|
||||
fetch("/api/users")
|
||||
.then((r) => r.json())
|
||||
.then(setUsers);
|
||||
}, []);
|
||||
}
|
||||
```
|
||||
|
||||
**Correct (multiple instances share one request):**
|
||||
|
||||
```tsx
|
||||
import useSWR from "swr";
|
||||
|
||||
function UserList() {
|
||||
const { data: users } = useSWR("/api/users", fetcher);
|
||||
}
|
||||
```
|
||||
|
||||
**For immutable data:**
|
||||
|
||||
```tsx
|
||||
import { useImmutableSWR } from "@/lib/swr";
|
||||
|
||||
function StaticContent() {
|
||||
const { data } = useImmutableSWR("/api/config", fetcher);
|
||||
}
|
||||
```
|
||||
|
||||
**For mutations:**
|
||||
|
||||
```tsx
|
||||
import { useSWRMutation } from "swr/mutation";
|
||||
|
||||
function UpdateButton() {
|
||||
const { trigger } = useSWRMutation("/api/user", updateUser);
|
||||
return <button onClick={() => trigger()}>Update</button>;
|
||||
}
|
||||
```
|
||||
|
||||
Reference: [https://swr.vercel.app](https://swr.vercel.app)
|
||||
@@ -0,0 +1,110 @@
|
||||
---
|
||||
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.
|
||||
@@ -0,0 +1,80 @@
|
||||
---
|
||||
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)
|
||||
@@ -0,0 +1,28 @@
|
||||
---
|
||||
title: Cache Property Access in Loops
|
||||
impact: LOW-MEDIUM
|
||||
impactDescription: reduces lookups
|
||||
tags: javascript, loops, optimization, caching
|
||||
---
|
||||
|
||||
## Cache Property Access in Loops
|
||||
|
||||
Cache object property lookups in hot paths.
|
||||
|
||||
**Incorrect (3 lookups × N iterations):**
|
||||
|
||||
```typescript
|
||||
for (let i = 0; i < arr.length; i++) {
|
||||
process(obj.config.settings.value);
|
||||
}
|
||||
```
|
||||
|
||||
**Correct (1 lookup total):**
|
||||
|
||||
```typescript
|
||||
const value = obj.config.settings.value;
|
||||
const len = arr.length;
|
||||
for (let i = 0; i < len; i++) {
|
||||
process(value);
|
||||
}
|
||||
```
|
||||
@@ -0,0 +1,70 @@
|
||||
---
|
||||
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();
|
||||
}
|
||||
});
|
||||
```
|
||||
@@ -0,0 +1,32 @@
|
||||
---
|
||||
title: Combine Multiple Array Iterations
|
||||
impact: LOW-MEDIUM
|
||||
impactDescription: reduces iterations
|
||||
tags: javascript, arrays, loops, performance
|
||||
---
|
||||
|
||||
## Combine Multiple Array Iterations
|
||||
|
||||
Multiple `.filter()` or `.map()` calls iterate the array multiple times. Combine into one loop.
|
||||
|
||||
**Incorrect (3 iterations):**
|
||||
|
||||
```typescript
|
||||
const admins = users.filter((u) => u.isAdmin);
|
||||
const testers = users.filter((u) => u.isTester);
|
||||
const inactive = users.filter((u) => !u.isActive);
|
||||
```
|
||||
|
||||
**Correct (1 iteration):**
|
||||
|
||||
```typescript
|
||||
const admins: User[] = [];
|
||||
const testers: User[] = [];
|
||||
const inactive: User[] = [];
|
||||
|
||||
for (const user of users) {
|
||||
if (user.isAdmin) admins.push(user);
|
||||
if (user.isTester) testers.push(user);
|
||||
if (!user.isActive) inactive.push(user);
|
||||
}
|
||||
```
|
||||
@@ -0,0 +1,50 @@
|
||||
---
|
||||
title: Early Return from Functions
|
||||
impact: LOW-MEDIUM
|
||||
impactDescription: avoids unnecessary computation
|
||||
tags: javascript, functions, optimization, early-return
|
||||
---
|
||||
|
||||
## Early Return from Functions
|
||||
|
||||
Return early when result is determined to skip unnecessary processing.
|
||||
|
||||
**Incorrect (processes all items even after finding answer):**
|
||||
|
||||
```typescript
|
||||
function validateUsers(users: User[]) {
|
||||
let hasError = false;
|
||||
let errorMessage = "";
|
||||
|
||||
for (const user of users) {
|
||||
if (!user.email) {
|
||||
hasError = true;
|
||||
errorMessage = "Email required";
|
||||
}
|
||||
if (!user.name) {
|
||||
hasError = true;
|
||||
errorMessage = "Name required";
|
||||
}
|
||||
// Continues checking all users even after error found
|
||||
}
|
||||
|
||||
return hasError ? { valid: false, error: errorMessage } : { valid: true };
|
||||
}
|
||||
```
|
||||
|
||||
**Correct (returns immediately on first error):**
|
||||
|
||||
```typescript
|
||||
function validateUsers(users: User[]) {
|
||||
for (const user of users) {
|
||||
if (!user.email) {
|
||||
return { valid: false, error: "Email required" };
|
||||
}
|
||||
if (!user.name) {
|
||||
return { valid: false, error: "Name required" };
|
||||
}
|
||||
}
|
||||
|
||||
return { valid: true };
|
||||
}
|
||||
```
|
||||
@@ -0,0 +1,55 @@
|
||||
---
|
||||
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
|
||||
@@ -0,0 +1,45 @@
|
||||
---
|
||||
title: Hoist RegExp Creation
|
||||
impact: LOW-MEDIUM
|
||||
impactDescription: avoids recreation
|
||||
tags: javascript, regexp, optimization, memoization
|
||||
---
|
||||
|
||||
## Hoist RegExp Creation
|
||||
|
||||
Don't create RegExp inside render. Hoist to module scope or memoize with `useMemo()`.
|
||||
|
||||
**Incorrect (new RegExp every render):**
|
||||
|
||||
```tsx
|
||||
function Highlighter({ text, query }: Props) {
|
||||
const regex = new RegExp(`(${query})`, 'gi')
|
||||
const parts = text.split(regex)
|
||||
return <>{parts.map((part, i) => ...)}</>
|
||||
}
|
||||
```
|
||||
|
||||
**Correct (memoize or hoist):**
|
||||
|
||||
```tsx
|
||||
const EMAIL_REGEX = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
|
||||
|
||||
function Highlighter({ text, query }: Props) {
|
||||
const regex = useMemo(
|
||||
() => new RegExp(`(${escapeRegex(query)})`, 'gi'),
|
||||
[query]
|
||||
)
|
||||
const parts = text.split(regex)
|
||||
return <>{parts.map((part, i) => ...)}</>
|
||||
}
|
||||
```
|
||||
|
||||
**Warning (global regex has mutable state):**
|
||||
|
||||
Global regex (`/g`) has mutable `lastIndex` state:
|
||||
|
||||
```typescript
|
||||
const regex = /foo/g;
|
||||
regex.test("foo"); // true, lastIndex = 3
|
||||
regex.test("foo"); // false, lastIndex = 0
|
||||
```
|
||||
@@ -0,0 +1,37 @@
|
||||
---
|
||||
title: Build Index Maps for Repeated Lookups
|
||||
impact: LOW-MEDIUM
|
||||
impactDescription: 1M ops to 2K ops
|
||||
tags: javascript, map, indexing, optimization, performance
|
||||
---
|
||||
|
||||
## Build Index Maps for Repeated Lookups
|
||||
|
||||
Multiple `.find()` calls by the same key should use a Map.
|
||||
|
||||
**Incorrect (O(n) per lookup):**
|
||||
|
||||
```typescript
|
||||
function processOrders(orders: Order[], users: User[]) {
|
||||
return orders.map((order) => ({
|
||||
...order,
|
||||
user: users.find((u) => u.id === order.userId),
|
||||
}));
|
||||
}
|
||||
```
|
||||
|
||||
**Correct (O(1) per lookup):**
|
||||
|
||||
```typescript
|
||||
function processOrders(orders: Order[], users: User[]) {
|
||||
const userById = new Map(users.map((u) => [u.id, u]));
|
||||
|
||||
return orders.map((order) => ({
|
||||
...order,
|
||||
user: userById.get(order.userId),
|
||||
}));
|
||||
}
|
||||
```
|
||||
|
||||
Build map once (O(n)), then all lookups are O(1).
|
||||
For 1000 orders × 1000 users: 1M ops → 2K ops.
|
||||
@@ -0,0 +1,50 @@
|
||||
---
|
||||
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
|
||||
@@ -0,0 +1,82 @@
|
||||
---
|
||||
title: Use Loop for Min/Max Instead of Sort
|
||||
impact: LOW
|
||||
impactDescription: O(n) instead of O(n log n)
|
||||
tags: javascript, arrays, performance, sorting, algorithms
|
||||
---
|
||||
|
||||
## Use Loop for Min/Max Instead of Sort
|
||||
|
||||
Finding the smallest or largest element only requires a single pass through the array. Sorting is wasteful and slower.
|
||||
|
||||
**Incorrect (O(n log n) - sort to find latest):**
|
||||
|
||||
```typescript
|
||||
interface Project {
|
||||
id: string;
|
||||
name: string;
|
||||
updatedAt: number;
|
||||
}
|
||||
|
||||
function getLatestProject(projects: Project[]) {
|
||||
const sorted = [...projects].sort((a, b) => b.updatedAt - a.updatedAt);
|
||||
return sorted[0];
|
||||
}
|
||||
```
|
||||
|
||||
Sorts the entire array just to find the maximum value.
|
||||
|
||||
**Incorrect (O(n log n) - sort for oldest and newest):**
|
||||
|
||||
```typescript
|
||||
function getOldestAndNewest(projects: Project[]) {
|
||||
const sorted = [...projects].sort((a, b) => a.updatedAt - b.updatedAt);
|
||||
return { oldest: sorted[0], newest: sorted[sorted.length - 1] };
|
||||
}
|
||||
```
|
||||
|
||||
Still sorts unnecessarily when only min/max are needed.
|
||||
|
||||
**Correct (O(n) - single loop):**
|
||||
|
||||
```typescript
|
||||
function getLatestProject(projects: Project[]) {
|
||||
if (projects.length === 0) return null;
|
||||
|
||||
let latest = projects[0];
|
||||
|
||||
for (let i = 1; i < projects.length; i++) {
|
||||
if (projects[i].updatedAt > latest.updatedAt) {
|
||||
latest = projects[i];
|
||||
}
|
||||
}
|
||||
|
||||
return latest;
|
||||
}
|
||||
|
||||
function getOldestAndNewest(projects: Project[]) {
|
||||
if (projects.length === 0) return { oldest: null, newest: null };
|
||||
|
||||
let oldest = projects[0];
|
||||
let newest = projects[0];
|
||||
|
||||
for (let i = 1; i < projects.length; i++) {
|
||||
if (projects[i].updatedAt < oldest.updatedAt) oldest = projects[i];
|
||||
if (projects[i].updatedAt > newest.updatedAt) newest = projects[i];
|
||||
}
|
||||
|
||||
return { oldest, newest };
|
||||
}
|
||||
```
|
||||
|
||||
Single pass through the array, no copying, no sorting.
|
||||
|
||||
**Alternative (Math.min/Math.max for small arrays):**
|
||||
|
||||
```typescript
|
||||
const numbers = [5, 2, 8, 1, 9];
|
||||
const min = Math.min(...numbers);
|
||||
const max = Math.max(...numbers);
|
||||
```
|
||||
|
||||
This works for small arrays, but can be slower or just throw an error for very large arrays due to spread operator limitations. Maximal array length is approximately 124000 in Chrome 143 and 638000 in Safari 18; exact numbers may vary - see [the fiddle](https://jsfiddle.net/qw1jabsx/4/). Use the loop approach for reliability.
|
||||
@@ -0,0 +1,106 @@
|
||||
---
|
||||
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
|
||||
@@ -0,0 +1,24 @@
|
||||
---
|
||||
title: Use Set/Map for O(1) Lookups
|
||||
impact: LOW-MEDIUM
|
||||
impactDescription: O(n) to O(1)
|
||||
tags: javascript, set, map, data-structures, performance
|
||||
---
|
||||
|
||||
## Use Set/Map for O(1) Lookups
|
||||
|
||||
Convert arrays to Set/Map for repeated membership checks.
|
||||
|
||||
**Incorrect (O(n) per check):**
|
||||
|
||||
```typescript
|
||||
const allowedIds = ['a', 'b', 'c', ...]
|
||||
items.filter(item => allowedIds.includes(item.id))
|
||||
```
|
||||
|
||||
**Correct (O(1) per check):**
|
||||
|
||||
```typescript
|
||||
const allowedIds = new Set(['a', 'b', 'c', ...])
|
||||
items.filter(item => allowedIds.has(item.id))
|
||||
```
|
||||
@@ -0,0 +1,57 @@
|
||||
---
|
||||
title: Use toSorted() Instead of sort() for Immutability
|
||||
impact: MEDIUM-HIGH
|
||||
impactDescription: prevents mutation bugs in React state
|
||||
tags: javascript, arrays, immutability, react, state, mutation
|
||||
---
|
||||
|
||||
## Use toSorted() Instead of sort() for Immutability
|
||||
|
||||
`.sort()` mutates the array in place, which can cause bugs with React state and props. Use `.toSorted()` to create a new sorted array without mutation.
|
||||
|
||||
**Incorrect (mutates original array):**
|
||||
|
||||
```typescript
|
||||
function UserList({ users }: { users: User[] }) {
|
||||
// Mutates the users prop array!
|
||||
const sorted = useMemo(
|
||||
() => users.sort((a, b) => a.name.localeCompare(b.name)),
|
||||
[users]
|
||||
)
|
||||
return <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
|
||||
@@ -0,0 +1,26 @@
|
||||
---
|
||||
title: Use Activity Component for Show/Hide
|
||||
impact: MEDIUM
|
||||
impactDescription: preserves state/DOM
|
||||
tags: rendering, activity, visibility, state-preservation
|
||||
---
|
||||
|
||||
## Use Activity Component for Show/Hide
|
||||
|
||||
Use React's `<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.
|
||||
@@ -0,0 +1,38 @@
|
||||
---
|
||||
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.
|
||||
@@ -0,0 +1,32 @@
|
||||
---
|
||||
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>
|
||||
```
|
||||
@@ -0,0 +1,38 @@
|
||||
---
|
||||
title: CSS content-visibility for Long Lists
|
||||
impact: HIGH
|
||||
impactDescription: faster initial render
|
||||
tags: rendering, css, content-visibility, long-lists
|
||||
---
|
||||
|
||||
## CSS content-visibility for Long Lists
|
||||
|
||||
Apply `content-visibility: auto` to defer off-screen rendering.
|
||||
|
||||
**CSS:**
|
||||
|
||||
```css
|
||||
.message-item {
|
||||
content-visibility: auto;
|
||||
contain-intrinsic-size: 0 80px;
|
||||
}
|
||||
```
|
||||
|
||||
**Example:**
|
||||
|
||||
```tsx
|
||||
function MessageList({ messages }: { messages: Message[] }) {
|
||||
return (
|
||||
<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).
|
||||
@@ -0,0 +1,36 @@
|
||||
---
|
||||
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.
|
||||
@@ -0,0 +1,72 @@
|
||||
---
|
||||
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.
|
||||
+26
@@ -0,0 +1,26 @@
|
||||
---
|
||||
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>;
|
||||
}
|
||||
```
|
||||
@@ -0,0 +1,89 @@
|
||||
---
|
||||
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)
|
||||
@@ -0,0 +1,71 @@
|
||||
---
|
||||
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)
|
||||
@@ -0,0 +1,28 @@
|
||||
---
|
||||
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
|
||||
```
|
||||
@@ -0,0 +1,75 @@
|
||||
---
|
||||
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)
|
||||
@@ -0,0 +1,39 @@
|
||||
---
|
||||
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>;
|
||||
}
|
||||
```
|
||||
@@ -0,0 +1,45 @@
|
||||
---
|
||||
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]);
|
||||
```
|
||||
@@ -0,0 +1,40 @@
|
||||
---
|
||||
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)
|
||||
@@ -0,0 +1,29 @@
|
||||
---
|
||||
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"} />;
|
||||
}
|
||||
```
|
||||
@@ -0,0 +1,77 @@
|
||||
---
|
||||
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.
|
||||
@@ -0,0 +1,58 @@
|
||||
---
|
||||
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.
|
||||
@@ -0,0 +1,36 @@
|
||||
---
|
||||
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 />
|
||||
```
|
||||
@@ -0,0 +1,44 @@
|
||||
---
|
||||
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.
|
||||
@@ -0,0 +1,45 @@
|
||||
---
|
||||
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)
|
||||
@@ -0,0 +1,83 @@
|
||||
---
|
||||
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
@@ -0,0 +1,35 @@
|
||||
---
|
||||
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
|
||||
}
|
||||
```
|
||||
@@ -0,0 +1,64 @@
|
||||
---
|
||||
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.
|
||||
@@ -0,0 +1,40 @@
|
||||
---
|
||||
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);
|
||||
}, []);
|
||||
}
|
||||
```
|
||||
@@ -0,0 +1,59 @@
|
||||
---
|
||||
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)
|
||||
@@ -0,0 +1,73 @@
|
||||
---
|
||||
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)",
|
||||
}}
|
||||
/>
|
||||
);
|
||||
}
|
||||
```
|
||||
@@ -0,0 +1,74 @@
|
||||
---
|
||||
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)
|
||||
@@ -0,0 +1,96 @@
|
||||
---
|
||||
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)
|
||||
@@ -0,0 +1,41 @@
|
||||
---
|
||||
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)
|
||||
@@ -0,0 +1,76 @@
|
||||
---
|
||||
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)
|
||||
@@ -0,0 +1,65 @@
|
||||
---
|
||||
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.
|
||||
@@ -0,0 +1,145 @@
|
||||
---
|
||||
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.
|
||||
@@ -0,0 +1,83 @@
|
||||
---
|
||||
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>
|
||||
);
|
||||
}
|
||||
```
|
||||
@@ -0,0 +1,32 @@
|
||||
---
|
||||
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.
|
||||
@@ -0,0 +1,38 @@
|
||||
---
|
||||
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,62 +0,0 @@
|
||||
acodec
|
||||
adblocker
|
||||
ahooks
|
||||
aliyuncs
|
||||
antd
|
||||
aplus
|
||||
behaviour
|
||||
bili
|
||||
bilibili
|
||||
bodyparser
|
||||
bodys
|
||||
buildx
|
||||
cancle
|
||||
cliqz
|
||||
clsx
|
||||
commitlint
|
||||
compat
|
||||
Conpty
|
||||
consola
|
||||
conventionalcommits
|
||||
datetime
|
||||
DDTHH
|
||||
deeplink
|
||||
esmfile
|
||||
execa
|
||||
idtype
|
||||
immer
|
||||
inversify
|
||||
KHTML
|
||||
languagedetector
|
||||
localforage
|
||||
lucide
|
||||
mediago
|
||||
metas
|
||||
nocheck
|
||||
optimizelegibility
|
||||
outdir
|
||||
pinia
|
||||
Qrcode
|
||||
redownload
|
||||
Redownload
|
||||
reduxjs
|
||||
rmvb
|
||||
shadcn
|
||||
Sider
|
||||
stylelint
|
||||
svgr
|
||||
svgz
|
||||
tailwindcss
|
||||
TDAPP
|
||||
tiptap
|
||||
tseslint
|
||||
typeorm
|
||||
vaul
|
||||
vitepress
|
||||
vuedraggable
|
||||
vuejs
|
||||
waline
|
||||
watting
|
||||
Watting
|
||||
xgplayer
|
||||
zustand
|
||||
@@ -0,0 +1,22 @@
|
||||
**/node_modules
|
||||
**/build
|
||||
**/dist
|
||||
**/release
|
||||
**/.turbo
|
||||
**/.git
|
||||
**/.claude
|
||||
**/.deps
|
||||
*.md
|
||||
|
||||
# Go build artifacts
|
||||
apps/core/bin/
|
||||
apps/core/server
|
||||
|
||||
# Electron source (not needed, but keep package.json files for workspace/build)
|
||||
apps/electron/src/
|
||||
apps/electron/scripts/
|
||||
docs/
|
||||
|
||||
# OS files
|
||||
.DS_Store
|
||||
**/.DS_Store
|
||||
+15
-15
@@ -1,15 +1,15 @@
|
||||
# http://editorconfig.org
|
||||
root = true
|
||||
|
||||
[*]
|
||||
charset = utf-8
|
||||
end_of_line = lf
|
||||
indent_size = 2
|
||||
indent_style = space
|
||||
insert_final_newline = true
|
||||
max_line_length = 80
|
||||
trim_trailing_whitespace = true
|
||||
|
||||
[*.md]
|
||||
max_line_length = 0
|
||||
trim_trailing_whitespace = false
|
||||
# http://editorconfig.org
|
||||
root = true
|
||||
|
||||
[*]
|
||||
charset = utf-8
|
||||
end_of_line = lf
|
||||
indent_size = 2
|
||||
indent_style = space
|
||||
insert_final_newline = true
|
||||
max_line_length = 80
|
||||
trim_trailing_whitespace = true
|
||||
|
||||
[*.md]
|
||||
max_line_length = 0
|
||||
trim_trailing_whitespace = false
|
||||
|
||||
@@ -1,5 +1,3 @@
|
||||
# FIXME: APP_ 开头的会暴漏给前端
|
||||
APP_NAME=mediago
|
||||
APP_ID=mediago.ziying.site
|
||||
APP_NAME=mediago-community
|
||||
APP_ID=mediago.caorushizi.cn
|
||||
APP_COPYRIGHT=caorushizi
|
||||
APP_VERSION=3.0.0
|
||||
|
||||
+1
-1
@@ -1,5 +1,5 @@
|
||||
APP_TD_APPID=
|
||||
APP_SENTRY_DSN=
|
||||
|
||||
GH_TOKEN=
|
||||
LOAD_DEVTOOLS=
|
||||
DEBUG_PLUGINS=true
|
||||
|
||||
+1
-1
@@ -1,4 +1,4 @@
|
||||
APP_TD_APPID=
|
||||
APP_SENTRY_DSN=
|
||||
|
||||
GH_TOKEN=
|
||||
DEBUG_PLUGINS=false
|
||||
|
||||
@@ -0,0 +1,58 @@
|
||||
# GitHub Copilot Instruction: Code Review and Optimization
|
||||
|
||||
## Role and Objective
|
||||
|
||||
You are a **top-tier software architect and performance optimization expert**.
|
||||
Your goal is to help me — a senior TypeScript full-stack engineer — elevate the quality of my code to a new level.
|
||||
When reviewing my code, **do not explain basic concepts**. I need **precise, deep, and forward-thinking insights**.
|
||||
|
||||
Your core mission is **optimization**, including but not limited to:
|
||||
|
||||
- **Performance improvement**: Identify and optimize performance bottlenecks, reduce unnecessary computation and resource consumption.
|
||||
- **Code refactoring**: Suggest more elegant and efficient implementations to improve code structure.
|
||||
- **Design patterns**: Identify opportunities to apply or refine design patterns to enhance scalability and maintainability.
|
||||
- **Best practices**: Ensure the code adheres to the latest best practices for the TypeScript ecosystem (Node.js, React, API layers, build pipelines).
|
||||
- **Potential risks**: Anticipate and highlight deep issues such as concurrency problems, security vulnerabilities, or resource leaks.
|
||||
|
||||
---
|
||||
|
||||
## Review Perspective and Principles
|
||||
|
||||
1. **High-Standard Review**
|
||||
Review the code as if it were going to **production for millions of users** and needs to be **maintained long-term**.
|
||||
|
||||
2. **Deep Analysis, Not Surface Advice**
|
||||
Don’t focus on trivial issues like typos or syntax sugar.
|
||||
Instead, explain **why** a refactor or change matters — e.g.:
|
||||
|
||||
> “Switching from a synchronous file read to `fs.promises` can free the event loop, improving throughput under load.”
|
||||
|
||||
3. **Performance First**
|
||||
- Evaluate time and space complexity; suggest algorithmic or structural improvements.
|
||||
- Examine I/O, database queries, and network calls for efficiency — recommend batching, caching, or async processing.
|
||||
- Recommend appropriate data structures or API strategies for scalability (e.g., pagination, streaming responses).
|
||||
|
||||
4. **Architecture and Design**
|
||||
- Follow **SOLID** principles. Explicitly identify violations and propose refactoring approaches.
|
||||
- Encourage **composition over inheritance** and **dependency injection**.
|
||||
- Suggest modularization and clear separation between layers (e.g., API, service, repository, UI).
|
||||
|
||||
5. **Code Style and Standards**
|
||||
- Code must be clear, consistent, and self-explanatory.
|
||||
- Follow the project’s existing conventions unless the change brings substantial clarity or performance gain.
|
||||
- For complex logic, suggest adding comments explaining the **rationale (“why”)**, not just the **action (“what”)**.
|
||||
|
||||
---
|
||||
|
||||
## Specific Instructions
|
||||
|
||||
- **When reviewing code, include the optimized code snippet directly**, with short comments highlighting key changes and their reasoning.
|
||||
- **If you find potential bugs or unhandled edge cases**, explicitly point them out and provide a fix suggestion.
|
||||
- **Avoid subjective stylistic comments** unless they impact clarity, performance, or maintainability.
|
||||
- **When I ask “Can this code be optimized?”**, provide a holistic evaluation covering performance, readability, scalability, and maintainability.
|
||||
|
||||
---
|
||||
|
||||
At the end of every response, please add:
|
||||
|
||||
> “AI-generated suggestions may contain errors; use your own judgment when applying them.”
|
||||
@@ -1,7 +1,10 @@
|
||||
name: Deploy Downloader Docs.
|
||||
name: Deploy MediaGo Docs
|
||||
|
||||
on:
|
||||
push:
|
||||
paths:
|
||||
- "docs/**"
|
||||
- ".github/workflows/build-docs.yml"
|
||||
branches: ["master"]
|
||||
|
||||
workflow_dispatch:
|
||||
@@ -18,34 +21,39 @@ concurrency:
|
||||
env:
|
||||
BUCKET: downloader-docs
|
||||
ENDPOINT: oss-cn-beijing.aliyuncs.com
|
||||
ACCESS_KEY: LTAI5tLckcUrBtj7bCiUYwWz
|
||||
ACCESS_KEY: LTAI5tDrRjFUAvufpCJioz3b
|
||||
ACCESS_KEY_SECRET: ${{ secrets.ACCESS_KEY_SECRET }}
|
||||
|
||||
jobs:
|
||||
build:
|
||||
name: Build
|
||||
name: Build Docs
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v4
|
||||
uses: actions/checkout@v6
|
||||
|
||||
- uses: pnpm/action-setup@v5
|
||||
with:
|
||||
version: "10.15.0"
|
||||
run_install: false
|
||||
standalone: true
|
||||
|
||||
- name: Setup Node
|
||||
uses: actions/setup-node@v4
|
||||
uses: actions/setup-node@v6
|
||||
with:
|
||||
node-version: 20
|
||||
node-version: "24.14.0"
|
||||
cache: "pnpm"
|
||||
|
||||
- uses: pnpm/action-setup@v3
|
||||
with:
|
||||
version: latest
|
||||
run_install: true
|
||||
- name: Install dependencies
|
||||
run: pnpm install
|
||||
|
||||
- name: Build with Vitepress
|
||||
run: pnpm run docs:build
|
||||
run: pnpm docs:build
|
||||
|
||||
- name: Install Alibaba Cloud OSSUTIL
|
||||
- name: Install Alibaba Cloud ossutil
|
||||
run: wget http://gosspublic.alicdn.com/ossutil/1.6.10/ossutil64 && chmod +x ossutil64
|
||||
|
||||
- name: Configure Alibaba Cloud OSSUTIL
|
||||
- name: Configure Alibaba Cloud ossutil
|
||||
run: ./ossutil64 config -i ${ACCESS_KEY} -k ${ACCESS_KEY_SECRET} -e ${ENDPOINT} -c .ossutilconfig
|
||||
|
||||
- name: Upload the web folder to the chosen OSS bucket
|
||||
@@ -0,0 +1,72 @@
|
||||
# build.yml
|
||||
|
||||
# Workflow's name
|
||||
name: Build MediaGo App
|
||||
|
||||
# Workflow's trigger
|
||||
on:
|
||||
workflow_dispatch:
|
||||
|
||||
# Workflow's jobs
|
||||
jobs:
|
||||
# job's id
|
||||
release:
|
||||
# job's name
|
||||
name: build and release electron app
|
||||
|
||||
# the type of machine to run the job on
|
||||
runs-on: ${{ matrix.os }}
|
||||
|
||||
# create a build matrix for jobs
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
os: [windows-latest, macos-latest, macos-15-intel, ubuntu-latest]
|
||||
|
||||
# create steps
|
||||
steps:
|
||||
- name: Check out git repository
|
||||
uses: actions/checkout@v6
|
||||
|
||||
- uses: pnpm/action-setup@v5
|
||||
with:
|
||||
version: "10.15.0"
|
||||
run_install: false
|
||||
|
||||
- name: Install Node.js
|
||||
uses: actions/setup-node@v6
|
||||
with:
|
||||
node-version: "24.14.0"
|
||||
cache: "pnpm"
|
||||
|
||||
- name: Install Python
|
||||
uses: actions/setup-python@v6
|
||||
with:
|
||||
python-version: "3.10"
|
||||
|
||||
- name: Setup Go
|
||||
uses: actions/setup-go@v6
|
||||
with:
|
||||
go-version: "1.25.0"
|
||||
cache-dependency-path: |
|
||||
apps/core/go.sum
|
||||
|
||||
- name: Install swag
|
||||
run: go install github.com/swaggo/swag/cmd/swag@latest
|
||||
|
||||
- name: Install dependencies
|
||||
run: pnpm install
|
||||
|
||||
- name: Download third-party deps
|
||||
run: pnpm deps:download
|
||||
|
||||
- name: Build & release app
|
||||
run: pnpm release:electron
|
||||
env:
|
||||
GH_TOKEN: ${{ secrets.GH_TOKEN }}
|
||||
APP_TD_APPID: ${{ secrets.APP_TD_APPID }}
|
||||
|
||||
- uses: actions/upload-artifact@v6
|
||||
with:
|
||||
name: mediago-${{ matrix.os }}
|
||||
path: apps/electron/release/mediago-*
|
||||
@@ -0,0 +1,76 @@
|
||||
name: Build & Push Docker Image
|
||||
|
||||
on:
|
||||
workflow_dispatch:
|
||||
push:
|
||||
tags:
|
||||
- "v*"
|
||||
|
||||
env:
|
||||
REGISTRY: ghcr.io
|
||||
IMAGE_NAME: ${{ github.repository }}
|
||||
|
||||
jobs:
|
||||
docker:
|
||||
name: Build and push multi-arch image
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
contents: read
|
||||
packages: write
|
||||
|
||||
steps:
|
||||
- name: Checkout code
|
||||
uses: actions/checkout@v6
|
||||
|
||||
- name: Set up QEMU
|
||||
uses: docker/setup-qemu-action@v3
|
||||
|
||||
- name: Set up Docker Buildx
|
||||
uses: docker/setup-buildx-action@v4
|
||||
|
||||
- name: Login to GitHub Container Registry
|
||||
uses: docker/login-action@v4
|
||||
with:
|
||||
registry: ${{ env.REGISTRY }}
|
||||
username: ${{ github.actor }}
|
||||
password: ${{ secrets.GITHUB_TOKEN }}
|
||||
|
||||
- name: Docker meta
|
||||
id: meta
|
||||
uses: docker/metadata-action@v6
|
||||
with:
|
||||
images: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}
|
||||
tags: |
|
||||
# For version tags: v1.0.0 → 1.0.0 + latest (non-beta only)
|
||||
type=semver,pattern={{version}}
|
||||
type=raw,value=latest,enable=${{ startsWith(github.ref, 'refs/tags/v') && !contains(github.ref, 'beta') }}
|
||||
# For manual triggers: dev-{run_id}
|
||||
type=raw,value=dev-${{ github.run_id }},enable=${{ !startsWith(github.ref, 'refs/tags/') }}
|
||||
|
||||
- name: Build and push
|
||||
uses: docker/build-push-action@v7
|
||||
with:
|
||||
context: .
|
||||
platforms: linux/amd64,linux/arm64
|
||||
push: true
|
||||
tags: ${{ steps.meta.outputs.tags }}
|
||||
labels: ${{ steps.meta.outputs.labels }}
|
||||
cache-from: type=gha
|
||||
cache-to: type=gha,mode=max
|
||||
|
||||
- name: Build Summary
|
||||
run: |
|
||||
echo "### 🎉 Docker Image Published" >> $GITHUB_STEP_SUMMARY
|
||||
echo "" >> $GITHUB_STEP_SUMMARY
|
||||
echo "**Image:** \`${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}\`" >> $GITHUB_STEP_SUMMARY
|
||||
echo "**Platforms:** linux/amd64, linux/arm64" >> $GITHUB_STEP_SUMMARY
|
||||
echo "" >> $GITHUB_STEP_SUMMARY
|
||||
echo "**Tags:**" >> $GITHUB_STEP_SUMMARY
|
||||
echo "${{ steps.meta.outputs.tags }}" | while read tag; do
|
||||
echo "- \`${tag}\`" >> $GITHUB_STEP_SUMMARY
|
||||
done
|
||||
echo "" >> $GITHUB_STEP_SUMMARY
|
||||
echo "**Pull:**" >> $GITHUB_STEP_SUMMARY
|
||||
echo "\`\`\`bash" >> $GITHUB_STEP_SUMMARY
|
||||
echo "docker pull ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:latest" >> $GITHUB_STEP_SUMMARY
|
||||
echo "\`\`\`" >> $GITHUB_STEP_SUMMARY
|
||||
@@ -1,64 +0,0 @@
|
||||
# build.yml
|
||||
|
||||
# Workflow's name
|
||||
name: Build Downloader App.
|
||||
|
||||
# Workflow's trigger
|
||||
on:
|
||||
push:
|
||||
branches:
|
||||
- master
|
||||
workflow_dispatch:
|
||||
|
||||
# Workflow's jobs
|
||||
jobs:
|
||||
# job's id
|
||||
release:
|
||||
# job's name
|
||||
name: build and release electron app
|
||||
|
||||
# the type of machine to run the job on
|
||||
runs-on: ${{ matrix.os }}
|
||||
|
||||
# create a build matrix for jobs
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
os: [windows-latest, macos-latest, macos-13, ubuntu-latest]
|
||||
|
||||
# create steps
|
||||
steps:
|
||||
# step1: check out repository
|
||||
- name: Check out git repository
|
||||
uses: actions/checkout@v4
|
||||
|
||||
# step2: install node env
|
||||
- name: Install Node.js
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: 20
|
||||
|
||||
# step4: install python env
|
||||
- name: Install Python
|
||||
uses: actions/setup-python@v5
|
||||
with:
|
||||
python-version: "3.10"
|
||||
|
||||
# step5: install pnpm env
|
||||
- uses: pnpm/action-setup@v3
|
||||
with:
|
||||
version: latest
|
||||
run_install: true
|
||||
standalone: true
|
||||
|
||||
- name: Build & release app
|
||||
run: pnpm run release
|
||||
env:
|
||||
GH_TOKEN: ${{ secrets.GH_TOKEN }}
|
||||
APP_TD_APPID: ${{ secrets.APP_TD_APPID }}
|
||||
APP_CLARITY_APPID: ${{ secrets.APP_CLARITY_APPID}}
|
||||
|
||||
- uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: mediago-${{ matrix.os }}
|
||||
path: packages/main/release/mediago-*
|
||||
+13
-1
@@ -2,5 +2,17 @@ node_modules
|
||||
*.local
|
||||
.idea
|
||||
.parcel-cache
|
||||
.vitepress
|
||||
*.tsno.mjs
|
||||
.DS_Store
|
||||
log
|
||||
.turbo
|
||||
.claude
|
||||
.store
|
||||
release
|
||||
go.work.sum
|
||||
apps/core/bin/
|
||||
apps/electron/bin/
|
||||
apps/main/bin/
|
||||
.deps/
|
||||
|
||||
tmp/
|
||||
|
||||
@@ -1,13 +0,0 @@
|
||||
{
|
||||
"extends": [
|
||||
"development"
|
||||
],
|
||||
"hints": {
|
||||
"axe/text-alternatives": [
|
||||
"default",
|
||||
{
|
||||
"image-alt": "off"
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
@@ -1,5 +0,0 @@
|
||||
#!/usr/bin/env sh
|
||||
. "$(dirname -- "$0")/_/husky.sh"
|
||||
|
||||
npx --no -- commitlint --edit ${1}
|
||||
npm run commitlint ${1}
|
||||
+1
-4
@@ -1,4 +1 @@
|
||||
#!/usr/bin/env sh
|
||||
. "$(dirname "$0")/_/husky.sh"
|
||||
|
||||
npx tsx ./scripts/pre-commit.ts
|
||||
lint-staged
|
||||
|
||||
@@ -1,3 +0,0 @@
|
||||
registry=https://registry.npmmirror.com
|
||||
electron_mirror=https://npmmirror.com/mirrors/electron/
|
||||
package-manager=pnpm
|
||||
@@ -0,0 +1,24 @@
|
||||
{
|
||||
"$schema": "./node_modules/oxfmt/configuration_schema.json",
|
||||
"printWidth": 80,
|
||||
"indentStyle": "space",
|
||||
"indentWidth": 2,
|
||||
"endOfLine": "lf",
|
||||
"sortPackageJson": false,
|
||||
"ignorePatterns": [
|
||||
"build",
|
||||
"dist",
|
||||
"release",
|
||||
"coverage",
|
||||
"docs/.vitepress/cache",
|
||||
"docs/.vitepress/dist"
|
||||
],
|
||||
"overrides": [
|
||||
{
|
||||
"files": ["*.md"],
|
||||
"options": {
|
||||
"proseWrap": "preserve"
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
{
|
||||
"$schema": "https://raw.githubusercontent.com/oxc-project/oxc/main/npm/oxlint/configuration_schema.json",
|
||||
"categories": {
|
||||
"correctness": "error",
|
||||
"suspicious": "warn",
|
||||
"perf": "warn",
|
||||
"pedantic": "off",
|
||||
"style": "off",
|
||||
"restriction": "off",
|
||||
"nursery": "off"
|
||||
},
|
||||
"rules": {
|
||||
"no-unused-vars": "error",
|
||||
"no-console": "warn",
|
||||
"no-debugger": "error",
|
||||
"no-duplicate-imports": "error",
|
||||
"eqeqeq": "warn",
|
||||
"typescript/no-explicit-any": "warn",
|
||||
"typescript/no-non-null-assertion": "warn",
|
||||
"import/no-duplicates": "error",
|
||||
"import/no-self-import": "error",
|
||||
"unicorn/no-null": "off",
|
||||
"unicorn/prefer-node-protocol": "error"
|
||||
},
|
||||
"overrides": [
|
||||
{
|
||||
"files": ["**/*.tsx", "**/*.jsx"],
|
||||
"rules": {
|
||||
"react/jsx-no-duplicate-props": "error",
|
||||
"react/no-direct-mutation-state": "error",
|
||||
"react/jsx-key": "error",
|
||||
"react-hooks/rules-of-hooks": "error",
|
||||
"react-hooks/exhaustive-deps": "warn"
|
||||
}
|
||||
},
|
||||
{
|
||||
"files": ["**/*.test.ts", "**/*.test.tsx", "**/*.spec.ts"],
|
||||
"rules": {
|
||||
"no-console": "off",
|
||||
"typescript/no-explicit-any": "off"
|
||||
}
|
||||
}
|
||||
],
|
||||
"ignorePatterns": [
|
||||
"node_modules",
|
||||
"build",
|
||||
"dist",
|
||||
"release",
|
||||
"*.min.js",
|
||||
"docs/.vitepress/cache",
|
||||
"docs/.vitepress/dist"
|
||||
]
|
||||
}
|
||||
@@ -1,3 +0,0 @@
|
||||
# Ignore artifacts:
|
||||
build
|
||||
coverage
|
||||
@@ -1 +0,0 @@
|
||||
{}
|
||||
Vendored
+4
@@ -0,0 +1,4 @@
|
||||
{
|
||||
"recommendations": ["oxc.oxc-vscode", "EditorConfig.EditorConfig"],
|
||||
"unwantedRecommendations": ["esbenp.prettier-vscode"]
|
||||
}
|
||||
Vendored
+15
@@ -0,0 +1,15 @@
|
||||
{
|
||||
"cSpell.words": ["intlify", "unplugin", "vitepress", "waline"],
|
||||
"oxc.enable": true,
|
||||
"oxc.lint.enable": true,
|
||||
"oxc.fmt.experimental": true,
|
||||
"editor.defaultFormatter": "oxc.oxc-vscode",
|
||||
"editor.formatOnSave": true,
|
||||
"editor.codeActionsOnSave": {
|
||||
"source.fixAll.oxc": "explicit"
|
||||
},
|
||||
"prettier.enable": false,
|
||||
"[go]": {
|
||||
"editor.defaultFormatter": "golang.go"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
# Repository Guidelines
|
||||
|
||||
## Project Structure & Module Organization
|
||||
|
||||
MediaGo is a pnpm/turborepo monorepo. Feature apps live in `apps/` (`frontend-main`, `frontend-mobile`, `backend-web`, `backend-electron`) for the user surfaces and API. Reusable logic stays in `packages/` (`shared` for cross-runtime helpers, `backend` for orchestration, `main` for Electron packaging). Long-form docs and assets sit in `docs/`, `images/`, and `docker/`. End-to-end checks live in `tests/`.
|
||||
|
||||
## Build, Test, and Development Commands
|
||||
|
||||
Run `pnpm install` once per clone. Use `pnpm dev` for the unified desktop + web experience, or scope to `pnpm dev:web` / `pnpm dev:electron`. `pnpm build` triggers the production Turborepo pipeline; `pnpm build:web-release` plus `pnpm build:docker` produce the deployable web bundle. Keep the codebase healthy with `pnpm lint`, `pnpm lint:fix`, `pnpm format`, and verify types through `pnpm types`.
|
||||
|
||||
## Coding Style & Naming Conventions
|
||||
|
||||
Target modern TypeScript with ES modules, two-space indentation, UTF-8, and LF endings per `.editorconfig`. Components, hooks, and services adopt PascalCase (e.g. `UserPreferencesPanel.tsx`). Utilities and helpers stay camelCase, and constants use SCREAMING_SNAKE_CASE. Always run `pnpm format` before committing; reserve comments for clarifying complex logic.
|
||||
|
||||
## Testing Guidelines
|
||||
|
||||
Integration suites live under `tests/*.test.ts` and execute via `pnpm test` using the Node `tsx` runner. Name files descriptively like `download.queue.integration.test.ts`. Mock external services, prefer shared fixtures in `tests/fixtures/`, and cover happy path, recovery, and edge behaviors when touching runtime code.
|
||||
|
||||
## Commit & Pull Request Guidelines
|
||||
|
||||
Follow Conventional Commits (e.g. `feat(frontend-main): add download queue UI`) and use `pnpm commit` (Commitizen) to stay compliant. Pull requests should summarize the change, link issues with `Closes #123`, note local test runs (`pnpm test`), and attach screenshots or recordings for UI updates. Call out new environment variables, migrations, or follow-up tasks so reviewers can reproduce the setup quickly.
|
||||
@@ -0,0 +1,93 @@
|
||||
# CLAUDE.md
|
||||
|
||||
This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.
|
||||
|
||||
## Project Overview
|
||||
|
||||
MediaGo is a cross-platform video downloader supporting m3u8/HLS streams. The codebase is a pnpm monorepo with three products:
|
||||
|
||||
1. **Desktop app** (`apps/electron` + `apps/ui`) — Electron wrapper that launches Go Core as a subprocess
|
||||
2. **Web server** (`apps/server` + `apps/ui`) — Node.js launcher that spawns Go Core as a subprocess
|
||||
3. **Video player** (`apps/core` + `apps/player-ui`) — Player UI embedded in Go Core for video playback
|
||||
|
||||
All three products share the Go Core backend (`apps/core`) for download orchestration.
|
||||
|
||||
## Common Commands
|
||||
|
||||
```bash
|
||||
pnpm install # Install all dependencies (run once per clone)
|
||||
pnpm dev:electron # Start Electron desktop dev environment (HMR)
|
||||
pnpm dev:server # Start server dev environment (HMR)
|
||||
pnpm build:electron # Production build for Electron
|
||||
pnpm build:web # Build UI only (server mode)
|
||||
pnpm core:dev # Start Go Core dev server (port 9900)
|
||||
pnpm core:build # Compile Go Core binary
|
||||
pnpm player:dev # Start Player dev (alias for core:dev)
|
||||
pnpm player:build # Build Player (alias for core:build)
|
||||
pnpm deps:download # Download third-party tools (ffmpeg, BBDown, etc.)
|
||||
pnpm deps:download:all # Download tools for all platforms
|
||||
pnpm lint # Lint with oxlint
|
||||
pnpm lint:fix # Auto-fix lint issues
|
||||
pnpm format # Format with oxfmt
|
||||
pnpm format:check # Check formatting without modifying
|
||||
pnpm check # Full check: lint + format + type check
|
||||
pnpm type:check # TypeScript type checking via Turborepo
|
||||
pnpm pack:electron # Build + package Electron distributable
|
||||
```
|
||||
|
||||
Commits use Conventional Commits format (e.g. `feat(electron): add queue UI`).
|
||||
|
||||
## Architecture
|
||||
|
||||
### Monorepo Layout
|
||||
|
||||
**Apps:**
|
||||
|
||||
- **`apps/core/`** — Go (Gin) REST API backend for download orchestration. Runs on port 9900. Uses SQLite (GORM), SSE for real-time events, PTY for capturing download tool output. Built with Gulp + Go cross-compilation.
|
||||
- **`apps/electron/`** — Electron main process (tsdown build, inversify DI). Launches Go Core via `@mediago/service-runner`.
|
||||
- **`apps/server/`** — Node.js launcher (tsdown build). Spawns Go Core via `@mediago/service-runner`.
|
||||
- **`apps/ui/`** — Shared React 19 frontend (Vite 8, Ant Design 6, Zustand, TailwindCSS 4, i18next). Used by both Electron and server targets.
|
||||
- **`apps/player-ui/`** — React 19 frontend for player (Vite 8, shadcn/ui, video.js, TailwindCSS 4). Built assets are embedded into Go Core via `//go:embed`.
|
||||
|
||||
**Packages:**
|
||||
|
||||
- **`packages/shared/common/`** — Platform-agnostic shared types, constants, and utilities
|
||||
- **`packages/core-sdk/`** — TypeScript SDK for Go Core REST API (Axios, SSE via eventsource)
|
||||
- **`packages/electron-preload/`** — Electron preload scripts for IPC bridge
|
||||
- **`packages/browser-extension/`** — Browser extension (Lit web components)
|
||||
- **`docs/`** — VitePress documentation (Chinese, English, Japanese)
|
||||
|
||||
### Multi-Target Build
|
||||
|
||||
The `APP_TARGET` env var (`electron` | `server`) controls which backend the UI builds against. Both targets share the same React UI but connect via different transports:
|
||||
|
||||
- **Electron**: IPC bridge (preload) + Go Core direct (via `@mediago/core-sdk`)
|
||||
- **Server/Web**: HTTP/WebSocket + Go Core direct (via `@mediago/core-sdk`)
|
||||
|
||||
The UI adapter layer (`apps/ui/src/hooks/adapters/`) abstracts this: `electron.ts` provides IPC bridge in desktop mode, `platform-stubs.ts` provides no-op stubs in web mode, and `index.ts` exports `platformApi` which selects the appropriate adapter.
|
||||
|
||||
### Key Patterns
|
||||
|
||||
- **Go Core as subprocess**: Both Electron and server apps launch Go Core via `@mediago/service-runner`, which manages the process lifecycle and port allocation
|
||||
- **Dependency Injection**: inversify with `@inversifyjs/binding-decorators` in Electron backend
|
||||
- **State Management**: Zustand in the UI
|
||||
- **Real-time events**: Go Core emits SSE events (`/api/events`); the UI's `api/events.ts` subscribes and dispatches to React via a listener pattern
|
||||
- **TypeScript**: Strict mode with experimental decorators and decorator metadata enabled
|
||||
- **Module format**: ES Modules everywhere
|
||||
|
||||
## Tooling
|
||||
|
||||
- **Package manager**: pnpm 10.15.0 (enforced via `packageManager` field)
|
||||
- **Build orchestration**: Turborepo
|
||||
- **App bundling**: tsdown for Node/Electron, Vite 8 for UI apps
|
||||
- **Go builds**: Gulp orchestrating `go build` / `go run` in `apps/core`
|
||||
- **Linter**: oxlint (config in `.oxlintrc.json`)
|
||||
- **Formatter**: oxfmt (config in `.oxfmtrc.json`)
|
||||
- **Pre-commit**: husky + lint-staged (runs oxlint --fix + oxfmt --write on staged files)
|
||||
- **Electron packaging**: electron-builder
|
||||
|
||||
## Style Conventions
|
||||
|
||||
- TypeScript, ES modules, 2-space indentation, UTF-8, LF endings
|
||||
- Components: PascalCase. Utilities: camelCase. Constants: SCREAMING_SNAKE_CASE
|
||||
- UI port: 8555 (strict). Go Core port: 9900. Player UI port: 8556
|
||||
+108
-25
@@ -1,34 +1,117 @@
|
||||
FROM m.daocloud.io/docker.io/library/node:20 AS builder
|
||||
# Build context: repository root
|
||||
# docker build -t mediago .
|
||||
|
||||
# ===== Stage 1: Node Builder (runs natively on build machine) =====
|
||||
FROM --platform=$BUILDPLATFORM node:22-bookworm-slim AS node-builder
|
||||
|
||||
RUN apt-get update && apt-get install -y --no-install-recommends unzip && rm -rf /var/lib/apt/lists/*
|
||||
RUN corepack enable && corepack prepare pnpm@10.15.0 --activate
|
||||
|
||||
# Map Docker TARGETARCH to Node arch naming for deps download
|
||||
ARG TARGETARCH
|
||||
RUN if [ "$TARGETARCH" = "amd64" ]; then \
|
||||
echo "linux-x64" > /tmp/deps-platform; \
|
||||
else \
|
||||
echo "linux-${TARGETARCH}" > /tmp/deps-platform; \
|
||||
fi
|
||||
|
||||
WORKDIR /src
|
||||
|
||||
# Install dependencies — copy all workspace package.json files first for caching
|
||||
COPY pnpm-lock.yaml pnpm-workspace.yaml package.json .npmrc* ./
|
||||
COPY apps/ui/package.json apps/ui/package.json
|
||||
COPY apps/player-ui/package.json apps/player-ui/package.json
|
||||
COPY apps/server/package.json apps/server/package.json
|
||||
COPY apps/core/package.json apps/core/package.json
|
||||
COPY apps/electron/package.json apps/electron/package.json
|
||||
COPY packages/ packages/
|
||||
RUN pnpm install --frozen-lockfile
|
||||
|
||||
# Copy source files and root configs needed by builds
|
||||
COPY tsconfig*.json turbo.json .env* ./
|
||||
COPY apps/ui/ apps/ui/
|
||||
COPY apps/player-ui/ apps/player-ui/
|
||||
COPY apps/electron/app/package.json apps/electron/app/package.json
|
||||
COPY scripts/ scripts/
|
||||
|
||||
# Build player-ui (will be embedded in Go core binary)
|
||||
RUN pnpm --filter @mediago/player-ui run build
|
||||
|
||||
# Build web UI for server mode
|
||||
ENV APP_TARGET=server
|
||||
ENV NODE_ENV=production
|
||||
RUN pnpm build:web
|
||||
|
||||
# Download third-party tools for TARGET platform
|
||||
RUN pnpm deps:download --platform $(cat /tmp/deps-platform)
|
||||
|
||||
# ===== Stage 2: Go Builder =====
|
||||
FROM --platform=$BUILDPLATFORM golang:1.25-bookworm AS go-builder
|
||||
|
||||
ARG TARGETOS=linux
|
||||
ARG TARGETARCH=amd64
|
||||
|
||||
WORKDIR /src
|
||||
|
||||
# Cache Go module downloads
|
||||
COPY apps/core/go.mod apps/core/go.sum apps/core/
|
||||
RUN cd apps/core && go mod download
|
||||
|
||||
# Copy Go source
|
||||
COPY apps/core/ apps/core/
|
||||
|
||||
# Copy player-ui dist into assets for go:embed
|
||||
COPY --from=node-builder /src/apps/player-ui/dist apps/core/assets/player/
|
||||
|
||||
# Ensure all dependencies are downloaded (go.sum may have been updated)
|
||||
RUN cd apps/core && go mod download
|
||||
|
||||
# Build Go core binary (cross-compile, no CGO)
|
||||
RUN cd apps/core && \
|
||||
CGO_ENABLED=0 GOOS=${TARGETOS} GOARCH=${TARGETARCH} \
|
||||
go build -trimpath -ldflags="-s -w" -o /out/mediago-core ./cmd/server
|
||||
|
||||
# ===== Stage 3: Runtime =====
|
||||
FROM debian:bookworm-slim
|
||||
|
||||
RUN apt-get update && \
|
||||
apt-get install -y --no-install-recommends ca-certificates libicu72 && \
|
||||
rm -rf /var/lib/apt/lists/*
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
COPY ./packages/backend/dist /app
|
||||
# Core binary
|
||||
COPY --from=go-builder /out/mediago-core /usr/local/bin/mediago-core
|
||||
|
||||
COPY ./packages/backend/package*.json ./
|
||||
# Web UI static files
|
||||
COPY --from=node-builder /src/apps/ui/build/server /app/static
|
||||
|
||||
RUN npm install --omit=dev --registry=https://registry.npmmirror.com
|
||||
# Third-party tools — copy from the platform-specific directory
|
||||
ARG TARGETARCH
|
||||
COPY --from=node-builder /src/.deps/linux-* /app/deps-tmp/
|
||||
RUN mkdir -p /app/deps && \
|
||||
if [ -d /app/deps-tmp ]; then \
|
||||
find /app/deps-tmp -type f -exec cp {} /app/deps/ \; ; \
|
||||
fi && \
|
||||
chmod +x /app/deps/* 2>/dev/null || true && \
|
||||
rm -rf /app/deps-tmp
|
||||
|
||||
RUN npm rebuild
|
||||
|
||||
# FROM m.daocloud.io/docker.io/library/debian:11-slim AS deb_extractor
|
||||
|
||||
# RUN cd /tmp && \
|
||||
# apt-get update && apt-get download libicu-dev && \
|
||||
# mkdir /dpkg && \
|
||||
# for deb in *.deb; do dpkg --extract $deb /dpkg || exit 10; done
|
||||
|
||||
# FROM gcr.io/distroless/nodejs20-debian12
|
||||
FROM m.daocloud.io/docker.io/library/node:20-bookworm-slim
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
COPY --from=builder /app /app
|
||||
|
||||
# COPY --from=deb_extractor /dpkg /
|
||||
RUN apt-get update && apt-get install -y libicu-dev ffmpeg
|
||||
|
||||
RUN npm install pm2 -g
|
||||
RUN mkdir -p /app/mediago/data /app/mediago/logs /app/mediago/downloads
|
||||
|
||||
EXPOSE 8899
|
||||
|
||||
CMD ["pm2-runtime", "server/index.js"]
|
||||
VOLUME ["/app/mediago"]
|
||||
|
||||
CMD ["mediago-core", \
|
||||
"--port=8899", \
|
||||
"--static-dir=/app/static", \
|
||||
"--enable-auth", \
|
||||
"--db-path=/app/mediago/data/mediago.db", \
|
||||
"--config-dir=/app/mediago/data", \
|
||||
"--log-dir=/app/mediago/logs", \
|
||||
"--local-dir=/app/mediago/downloads", \
|
||||
"--m3u8-bin=/app/deps/N_m3u8DL-RE", \
|
||||
"--bilibili-bin=/app/deps/BBDown", \
|
||||
"--direct-bin=/app/deps/aria2c", \
|
||||
"--mediago-bin=/app/deps/mediago", \
|
||||
"--ffmpeg-bin=/app/deps/ffmpeg"]
|
||||
|
||||
+151
@@ -0,0 +1,151 @@
|
||||
<div align="center">
|
||||
<h1>MediaGo</h1>
|
||||
<a href="https://downloader.caorushizi.cn/jp/guides.html?form=github">早く始めます</a>
|
||||
<span> • </span>
|
||||
<a href="https://downloader.caorushizi.cn/jp?form=github">公式サイトです</a>
|
||||
<span> • </span>
|
||||
<a href="https://downloader.caorushizi.cn/jp/documents.html?form=github">にやすりをかける</a>
|
||||
<span> • </span>
|
||||
<a href="https://github.com/caorushizi/mediago/discussions">Discussions</a>
|
||||
<br>
|
||||
<!-- MediaGo Pro -->
|
||||
<a href="https://mediago.torchstellar.com/?from=github">
|
||||
<img src="https://img.shields.io/badge/✨_新登場-MediaGo_Pro-ff6b6b?style=for-the-badge&logo=data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCAyNCAyNCIgZmlsbD0id2hpdGUiPjxwYXRoIGQ9Ik0xMiAyTDMgN2wzIDMgNi00IDYgNCAzLTMtOS01eiIvPjxwYXRoIGQ9Ik0zIDE3bDkgNSA5LTUtMy0zLTYgNC02LTQtMyAzeiIvPjwvc3ZnPg==" alt="MediaGo Pro" />
|
||||
</a>
|
||||
<a href="https://mediago.torchstellar.com/?from=github">
|
||||
<img src="https://img.shields.io/badge/🚀_今すぐ試す-オンライン版_インストール不要-2a82f6?style=for-the-badge" alt="Try Now" />
|
||||
</a>
|
||||
<br>
|
||||
<br>
|
||||
|
||||
<img alt="GitHub Downloads (all assets, all releases)" src="https://img.shields.io/github/downloads/caorushizi/mediago/total">
|
||||
<img alt="GitHub Downloads (all assets, latest release)" src="https://img.shields.io/github/downloads/caorushizi/mediago/latest/total">
|
||||
<img alt="GitHub Repo stars" src="https://img.shields.io/github/stars/caorushizi/mediago">
|
||||
<img alt="GitHub forks" src="https://img.shields.io/github/forks/caorushizi/mediago">
|
||||
<br>
|
||||
<br>
|
||||
|
||||
<a href="https://trendshift.io/repositories/11083" target="_blank">
|
||||
<img src="https://trendshift.io/api/badge/repositories/11083" alt="caorushizi%2Fmediago | Trendshift" style="width: 250px; height: 55px;" width="250" height="55"/>
|
||||
</a>
|
||||
|
||||
<hr />
|
||||
</div>
|
||||
|
||||
## Intro
|
||||
|
||||
本プロジェクトはm3u8ビデオ抽出ツール、ストリーミングダウンロード、m3u8ダウンロードをサポートしています。
|
||||
|
||||
- **✅ パケットキャプチャ不要**: ソフトウェアに内蔵されたブラウザを使用して、ウェブページ内のビデオリソースを簡単に検出し、検出したリソースリストからダウンロードしたいリソースを選択することで、シンプルかつ迅速にダウンロードできます。
|
||||
- **📱 モバイル再生**: PCとモバイルデバイス間で簡単にシームレスに切り替えが可能で、ダウンロードが完了した後はスマートフォンでビデオを視聴できます。
|
||||
- **⚡️ バッチダウンロード**: 複数のビデオやライブストリームリソースを同時にダウンロードでき、高速帯域幅を無駄にしません。
|
||||
- **🎉 Dockerデプロイメントサポート**: WebエンドをDockerでデプロイすることができ、簡単かつ便利です。
|
||||
|
||||
## Quickstart
|
||||
|
||||
コードを実行するには、Node.jsとpnpmが必要です。Node.jsは公式ウェブサイトからダウンロードしてインストールし、pnpmは`npm i -g pnpm`コマンドでインストールできます。
|
||||
|
||||
## コードの実行
|
||||
|
||||
```shell
|
||||
# コードのダウンロードです
|
||||
git clone https://github.com/caorushizi/mediago.git
|
||||
|
||||
# インストール依存症です
|
||||
pnpm i
|
||||
|
||||
# 開発環境です
|
||||
pnpm dev
|
||||
|
||||
# 梱包して運行します
|
||||
pnpm release
|
||||
|
||||
# dockerミラーリングを構築します
|
||||
docker buildx build -t caorushizi/mediago:latest .
|
||||
|
||||
# docker启动
|
||||
docker run -d --name mediago -p 8899:8899 -v /root/mediago:/root/mediago registry.cn-beijing.aliyuncs.com/caorushizi/mediago
|
||||
|
||||
```
|
||||
|
||||
## Releases
|
||||
|
||||
### v3.0.0 (2024.10.7 発売)
|
||||
|
||||
#### ソフトウェアダウンロード
|
||||
|
||||
- [【mediago】 windows(インストーラー版) v3.0.0](https://github.com/caorushizi/mediago/releases/download/v3.0.0/mediago-setup-win32-x64-3.0.0.exe)
|
||||
- [【mediago】 windows(ポータブル版) v3.0.0](https://github.com/caorushizi/mediago/releases/download/v3.0.0/mediago-portable-win32-x64-3.0.0.exe)
|
||||
- [【mediago】 macos arm64(Appleチップ) v3.0.0](https://github.com/caorushizi/mediago/releases/download/v3.0.0/mediago-setup-darwin-arm64-3.0.0.dmg)
|
||||
- [【mediago】 macos x64(Intelチップ) v3.0.0](https://github.com/caorushizi/mediago/releases/download/v3.0.0/mediago-setup-darwin-x64-3.0.0.dmg)
|
||||
- [【mediago】 linux v3.0.0](https://github.com/caorushizi/mediago/releases/download/v3.0.0/mediago-setup-linux-amd64-3.0.0.deb)
|
||||
- 【mediago】 docker v3.0 `docker run -d --name mediago -p 8899:8899 -v /root/mediago:/root/mediago registry.cn-beijing.aliyuncs.com/caorushizi/mediago:v3.0.0`
|
||||
|
||||
#### 国内ダウンロード
|
||||
|
||||
- [【mediago】 windows(インストーラー版) v3.0.0](https://static.ziying.site/mediago/mediago-setup-win32-x64-3.0.0.exe)
|
||||
- [【mediago】 windows(ポータブル版) v3.0.0](https://static.ziying.site/mediago/mediago-portable-win32-x64-3.0.0.exe)
|
||||
- [【mediago】 macos arm64(Appleチップ) v3.0.0](https://static.ziying.site/mediago/mediago-setup-darwin-arm64-3.0.0.dmg)
|
||||
- [【mediago】 macos x64(Intelチップ) v3.0.0](https://static.ziying.site/mediago/mediago-setup-darwin-x64-3.0.0-beta.5.dmg)
|
||||
- [【mediago】 linux v3.0.0](https://static.ziying.site/mediago/mediago-setup-linux-amd64-3.0.0.deb)
|
||||
- 【mediago】 docker v3.0 `docker run -d --name mediago -p 8899:8899 -v /root/mediago:/root/mediago registry.cn-beijing.aliyuncs.com/caorushizi/mediago:v3.0.0`
|
||||
|
||||
### docker 宝塔パネルワンクリックデプロイ(推奨)
|
||||
|
||||
1. 宝塔パネルをインストールし、[宝塔パネル](https://www.bt.cn/new/download.html?r=dk_mediago) の公式サイトから正式版のスクリプトを選択してインストールします。
|
||||
|
||||
2. インストール後、宝塔パネルにログインし、メニューから `Docker` をクリックします。初めてアクセスすると、`Docker` サービスをインストールするように指示されるので、「今すぐインストール」をクリックし、指示に従ってインストールを完了します。
|
||||
|
||||
3. インストールが完了したら、アプリストアで「MediaGo」を見つけ、インストールをクリックし、ドメイン名などの基本情報を設定してインストールを完了します。
|
||||
|
||||
### ソフトウェアスクリーンショット
|
||||
|
||||

|
||||
|
||||
### 重要な更新
|
||||
|
||||
- Web端のdockerデプロイをサポート
|
||||
- デスクトップ端のUIを更新
|
||||
|
||||
### 更新ログ
|
||||
|
||||
- デスクトップ端のUIを更新
|
||||
- Web端のdockerデプロイをサポート
|
||||
- 新たにビデオ再生機能を追加、デスクトップとモバイル端両方で再生可能
|
||||
- Macでの画面表示ができない問題を修正
|
||||
- バッチダウンロードのインタラクションを最適化
|
||||
- Windowsのポータブル版(インストール不要)を追加
|
||||
- ダウンロードリストの最適化、ページ内の複数のビデオリソースを嗅ぎ取る機能を追加
|
||||
- 手動でお気に入りリストのインポートとエクスポートをサポート
|
||||
- ホームページのダウンロードリストエクスポートをサポート
|
||||
- 「新規ダウンロード」フォームのインタラクションロジックを最適化
|
||||
- UrlSchemeでアプリを開き、ダウンロードタスクを追加する機能をサポート
|
||||
- バグの修正とユーザー体験の向上
|
||||
|
||||
## ソフトウェアスクリーンショット
|
||||
|
||||

|
||||
|
||||

|
||||
|
||||

|
||||
|
||||

|
||||
|
||||
## 技術スタック
|
||||
|
||||
- react <https://react.dev/>
|
||||
- electron <https://www.electronjs.org>
|
||||
- koa <https://koajs.com>
|
||||
- vite <https://cn.vitejs.dev>
|
||||
- antd <https://ant.design>
|
||||
- tailwindcss <https://tailwindcss.com>
|
||||
- shadcn <https://ui.shadcn.com/>
|
||||
- inversify <https://inversify.io>
|
||||
- typeorm <https://typeorm.io>
|
||||
|
||||
## 感謝
|
||||
|
||||
- N_m2u8DL-CLI は <https://github.com/nilaoda/N_m3u8DL-CLI> から来ています
|
||||
- N_m3u8DL-RE は <https://github.com/nilaoda/N_m3u8DL-RE> から来ています
|
||||
- mediago は <https://github.com/caorushizi/hls-downloader> から来ています
|
||||
@@ -1,121 +1,161 @@
|
||||
<img src="https://socialify.git.ci/caorushizi/mediago/image?font=Inter&forks=1&issues=1&language=1&name=1&owner=1&pattern=Circuit%20Board&pulls=1&stargazers=1&theme=Auto" alt="MediaDownloader"/>
|
||||
|
||||
<div align="center">
|
||||
<h1>MediaGo</h1>
|
||||
<a href="https://downloader.caorushizi.cn/guides.html?form=github">快速开始</a>
|
||||
<a href="https://downloader.caorushizi.cn/en/guides.html?form=github">Quick Start</a>
|
||||
<span> • </span>
|
||||
<a href="https://downloader.caorushizi.cn?form=github">官网</a>
|
||||
<a href="https://downloader.caorushizi.cn/en?form=github">Website</a>
|
||||
<span> • </span>
|
||||
<a href="https://downloader.caorushizi.cn/documents.html?form=github">文档</a>
|
||||
<a href="https://downloader.caorushizi.cn/en/documents.html?form=github">Docs</a>
|
||||
<span> • </span>
|
||||
<a href="https://github.com/caorushizi/mediago/discussions">Discussions</a>
|
||||
<br>
|
||||
|
||||
<a href="https://github.com/caorushizi/mediago/blob/master/README.zh.md">中文</a>
|
||||
<span> • </span>
|
||||
<a href="https://github.com/caorushizi/mediago/blob/master/README.jp.md">日本語</a>
|
||||
<br>
|
||||
|
||||
<!-- MediaGo Pro -->
|
||||
<a href="https://mediago.torchstellar.com/?from=github">
|
||||
<img src="https://img.shields.io/badge/✨_New_Release-MediaGo_Pro-ff6b6b?style=for-the-badge&logo=data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCAyNCAyNCIgZmlsbD0id2hpdGUiPjxwYXRoIGQ9Ik0xMiAyTDMgN2wzIDMgNi00IDYgNCAzLTMtOS01eiIvPjxwYXRoIGQ9Ik0zIDE3bDkgNSA5LTUtMy0zLTYgNC02LTQtMyAzeiIvPjwvc3ZnPg==" alt="MediaGo Pro" />
|
||||
</a>
|
||||
<a href="https://mediago.torchstellar.com/?from=github">
|
||||
<img src="https://img.shields.io/badge/🚀_Try_Now-Online_Version_No_Install-2a82f6?style=for-the-badge" alt="Try Now" />
|
||||
</a>
|
||||
<br>
|
||||
|
||||
<img alt="GitHub Downloads (all assets, all releases)" src="https://img.shields.io/github/downloads/caorushizi/mediago/total">
|
||||
<img alt="GitHub Downloads (all assets, latest release)" src="https://img.shields.io/github/downloads/caorushizi/mediago/latest/total">
|
||||
<img alt="GitHub Repo stars" src="https://img.shields.io/github/stars/caorushizi/mediago">
|
||||
<img alt="GitHub forks" src="https://img.shields.io/github/forks/caorushizi/mediago">
|
||||
<img alt="GitCode" src="https://gitcode.com/caorushizi/mediago/star/badge.svg">
|
||||
<br>
|
||||
|
||||
<a href="https://trendshift.io/repositories/11083" target="_blank">
|
||||
<img src="https://trendshift.io/api/badge/repositories/11083" alt="caorushizi%2Fmediago | Trendshift" style="width: 250px; height: 55px;" width="250" height="55"/>
|
||||
</a>
|
||||
|
||||
<hr />
|
||||
</div>
|
||||
|
||||
## Intro
|
||||
## What is MediaGo?
|
||||
|
||||
本项目支持 m3u8 视频在线提取工具 流媒体下载 m3u8 下载。
|
||||
A cross-platform streaming media downloader with built-in browser sniffing — grab m3u8, HLS, and more with zero packet-capture hassle.
|
||||
|
||||
- **✅ 无需抓包**: 使用软件自带浏览器可以轻松嗅探网页中的视频资源,通过嗅探到的资源列表选择自己想要下载的资源,简单快速。
|
||||
- **📱 移动播放**: 可以轻松无缝的在 PC 和移动设备之前切换,下载完成后即可使用手机观看视频。
|
||||
- **⚡️ 批量下载**: 支持同时下载多个视频和直播资源,高速带宽不闲置。
|
||||
- **🎉 支持 docker 部署**: 支持 docker 部署 web 端,方便快捷。
|
||||
- **✅ No packet capture needed** — The built-in browser automatically detects video resources on any page. Just pick what you want from the detected list and download.
|
||||
- **📱 Watch on mobile** — Seamlessly switch between PC and mobile. Once a video is downloaded, scan a QR code to watch it on your phone.
|
||||
- **⚡️ Batch downloads** — Download multiple videos and live streams at the same time — no wasted bandwidth.
|
||||
- **🎉 Docker support** — Deploy the web UI via Docker for quick, headless operation.
|
||||
- **🦞 OpenClaw Skill** — Download videos with natural language through AI coding assistants (OpenClaw, Claude Code, etc.). Install with `npx clawhub@latest install mediago`.
|
||||
|
||||
## Quickstart
|
||||
## Quick Start
|
||||
|
||||
运行代码需要 node 和 pnpm,node 需要在官网下载安装,pnpm 可以通过`npm i -g pnpm`安装。
|
||||
|
||||
## 运行代码
|
||||
You need **Node.js** and **pnpm**. Install Node.js from the [official site](https://nodejs.org/), then install pnpm:
|
||||
|
||||
```shell
|
||||
# 代码下载
|
||||
npm i -g pnpm
|
||||
```
|
||||
|
||||
## Running locally
|
||||
|
||||
```shell
|
||||
# Clone the repo
|
||||
git clone https://github.com/caorushizi/mediago.git
|
||||
|
||||
# 安装依赖
|
||||
pnpm i
|
||||
# Install dependencies
|
||||
pnpm install
|
||||
|
||||
# 开发环境
|
||||
pnpm dev
|
||||
# Start the Electron desktop app (dev mode)
|
||||
pnpm dev:electron
|
||||
|
||||
# 打包运行
|
||||
pnpm release
|
||||
# — or — start the web server (dev mode)
|
||||
pnpm dev:server
|
||||
|
||||
# 构建 docker 镜像
|
||||
docker buildx build -t caorushizi/mediago:latest .
|
||||
|
||||
# docker 启动
|
||||
docker run -d --name mediago -p 8899:8899 -v /root/mediago:/root/mediago registry.cn-beijing.aliyuncs.com/caorushizi/mediago
|
||||
# Package the Electron app for distribution
|
||||
pnpm pack:electron
|
||||
|
||||
# Package the web server for distribution
|
||||
pnpm pack:server
|
||||
```
|
||||
|
||||
## Releases
|
||||
|
||||
### v3.0.0 (2024.10.7 发布)
|
||||
### v3.5.0-beta.0 (Apr 3, 2026)
|
||||
|
||||
#### 软件下载
|
||||
#### Downloads
|
||||
|
||||
- [【mediago】 windows v2.2.3](https://github.com/caorushizi/mediago/releases/download/v2.2.3/mediago-setup-x64-2.2.3.exe)
|
||||
- [【mediago】 macos arm64 v2.2.3](https://github.com/caorushizi/mediago/releases/download/v2.2.3/mediago-setup-x64-2.2.3.dmg)
|
||||
- [【mediago】 macos x64 v2.2.3](https://github.com/caorushizi/mediago/releases/download/v2.2.3/mediago-setup-x64-2.2.3.dmg)
|
||||
- [【mediago】 linux v2.2.3](https://github.com/caorushizi/mediago/releases/download/v2.2.3/mediago-setup-arm64-2.2.3.dmg)
|
||||
- 【mediago】 docker v3.0 `docker run`
|
||||
- [Windows (installer) v3.5.0-beta.0](https://github.com/caorushizi/mediago/releases/download/v3.5.0-beta.0/mediago-community-setup-win32-x64-3.5.0-beta.0.exe)
|
||||
- [Windows (portable) v3.5.0-beta.0](https://github.com/caorushizi/mediago/releases/download/v3.5.0-beta.0/mediago-community-portable-win32-x64-3.5.0-beta.0.exe)
|
||||
- [macOS ARM64 (Apple Silicon) v3.5.0-beta.0](https://github.com/caorushizi/mediago/releases/download/v3.5.0-beta.0/mediago-community-setup-darwin-arm64-3.5.0-beta.0.dmg)
|
||||
- [macOS x64 (Intel) v3.5.0-beta.0](https://github.com/caorushizi/mediago/releases/download/v3.5.0-beta.0/mediago-community-setup-darwin-x64-3.5.0-beta.0.dmg)
|
||||
- [Linux v3.5.0-beta.0](https://github.com/caorushizi/mediago/releases/download/v3.5.0-beta.0/mediago-community-setup-linux-amd64-3.5.0-beta.0.deb)
|
||||
- Docker v3.5.0-beta.0: `docker run -d --name mediago -p 8899:8899 -v /path/to/mediago:/app/mediago ghcr.io/caorushizi/mediago:3.5.0-beta.0`
|
||||
|
||||
### 软件截图
|
||||
### v3.0.0 (Oct 7, 2024)
|
||||
|
||||

|
||||
#### Downloads
|
||||
|
||||
### 重要更新
|
||||
- [Windows (installer) v3.0.0](https://github.com/caorushizi/mediago/releases/download/v3.0.0/mediago-setup-win32-x64-3.0.0.exe)
|
||||
- [Windows (portable) v3.0.0](https://github.com/caorushizi/mediago/releases/download/v3.0.0/mediago-portable-win32-x64-3.0.0.exe)
|
||||
- [macOS ARM64 (Apple Silicon) v3.0.0](https://github.com/caorushizi/mediago/releases/download/v3.0.0/mediago-setup-darwin-arm64-3.0.0.dmg)
|
||||
- [macOS x64 (Intel) v3.0.0](https://github.com/caorushizi/mediago/releases/download/v3.0.0/mediago-setup-darwin-x64-3.0.0.dmg)
|
||||
- [Linux v3.0.0](https://github.com/caorushizi/mediago/releases/download/v3.0.0/mediago-setup-linux-amd64-3.0.0.deb)
|
||||
- Docker: `docker run -d --name mediago -p 8899:8899 -v /path/to/mediago:/app/mediago ghcr.io/caorushizi/mediago:latest`
|
||||
|
||||
- 支持 docker 部署 web 端
|
||||
- 更新桌面端 UI
|
||||
### One-click Docker deployment via BT Panel
|
||||
|
||||
### 更新日志
|
||||
1. Install [BT Panel](https://www.bt.cn/new/download.html?r=dk_mediago) using the official script.
|
||||
2. Log in to the panel, click **Docker** in the sidebar, and follow the prompts to install the Docker service.
|
||||
3. Find **MediaGo** in the app store, click **Install**, configure your domain, and you're done.
|
||||
|
||||
- 更新桌面端 UI
|
||||
- 支持 docker 部署 web 端
|
||||
- 新增视频播放,支持桌面端和移动端播放
|
||||
- 修复 mac 打开无法展示界面的问题
|
||||
- 优化了批量下载的交互
|
||||
- 添加了 windows 的便携版(免安装哦)
|
||||
- 优化了下载列表,支持页面中多个视频的嗅探
|
||||
- 支持收藏列表手动导入导出
|
||||
- 支持首页下载列表导出
|
||||
- 优化了【新建下载】表单的交互逻辑
|
||||
- 支持 UrlScheme 打开应用,并添加下载任务
|
||||
- 修复了一些 bug 并提升用户体验
|
||||
## Screenshots
|
||||
|
||||
## 软件截图
|
||||

|
||||
|
||||

|
||||

|
||||
|
||||

|
||||

|
||||
|
||||

|
||||

|
||||
|
||||

|
||||
## Changelog (v3.0.0)
|
||||
|
||||
## 技术栈
|
||||
- Docker deployment for the web UI
|
||||
- Redesigned desktop UI
|
||||
- Video playback on desktop and mobile
|
||||
- Fixed blank window on macOS launch
|
||||
- Improved batch download UX
|
||||
- Added Windows portable build (no install required)
|
||||
- Enhanced resource sniffing — detect multiple videos per page
|
||||
- Import / export favorites
|
||||
- Export the download list from the home page
|
||||
- Improved "New download" form flow
|
||||
- Open the app and add downloads via URL scheme
|
||||
- Various bug fixes and UX improvements
|
||||
|
||||
- react <https://react.dev/>
|
||||
- electron <https://www.electronjs.org>
|
||||
- koa <https://koajs.com>
|
||||
- vite <https://cn.vitejs.dev>
|
||||
- antd <https://ant.design>
|
||||
- tailwindcss <https://tailwindcss.com>
|
||||
- shadcn <https://ui.shadcn.com/>
|
||||
- inversify <https://inversify.io>
|
||||
- typeorm <https://typeorm.io>
|
||||
## Tech Stack
|
||||
|
||||
## 鸣谢
|
||||
- [React](https://react.dev/)
|
||||
- [Electron](https://www.electronjs.org)
|
||||
- [Koa](https://koajs.com)
|
||||
- [Vite](https://vitejs.dev)
|
||||
- [Ant Design](https://ant.design)
|
||||
- [Tailwind CSS](https://tailwindcss.com)
|
||||
- [shadcn/ui](https://ui.shadcn.com/)
|
||||
- [Inversify](https://inversify.io)
|
||||
|
||||
- N_m2u8DL-CLI 来自于 <https://github.com/nilaoda/N_m3u8DL-CLI>
|
||||
- N_m3u8DL-RE 来自于 <https://github.com/nilaoda/N_m3u8DL-RE>
|
||||
- mediago 来自于 <https://github.com/caorushizi/hls-downloader>
|
||||
## Acknowledgements
|
||||
|
||||
- [N_m3u8DL-RE](https://github.com/nilaoda/N_m3u8DL-RE)
|
||||
- [BBDown](https://github.com/nilaoda/BBDown)
|
||||
- [yt-dlp](https://github.com/yt-dlp/yt-dlp)
|
||||
- [mediago-core](https://github.com/caorushizi/mediago-core)
|
||||
|
||||
## Disclaimer
|
||||
|
||||
> **This project is for educational and research purposes only. Do not use it for any commercial or illegal purposes.**
|
||||
>
|
||||
> 1. All code and functionality provided by this project are intended solely as a reference for learning about streaming media technologies. Users must comply with the laws and regulations of their jurisdiction.
|
||||
> 2. Any content downloaded using this project remains the property of its original copyright holders. Users should delete downloaded content within 24 hours or obtain proper authorization.
|
||||
> 3. The developers of this project are not responsible for any actions taken by users, including but not limited to downloading copyrighted content or impacting third-party platforms.
|
||||
> 4. Using this project for mass scraping, disrupting platform services, or any activity that infringes upon the legitimate rights of others is strictly prohibited.
|
||||
> 5. By using this project you acknowledge that you have read and agree to this disclaimer. If you do not agree, stop using the project and delete it immediately.
|
||||
|
||||
+172
@@ -0,0 +1,172 @@
|
||||
<div align="center">
|
||||
<h1>MediaGo</h1>
|
||||
<a href="https://downloader.caorushizi.cn/guides.html?form=github">快速开始</a>
|
||||
<span> • </span>
|
||||
<a href="https://downloader.caorushizi.cn?form=github">官网</a>
|
||||
<span> • </span>
|
||||
<a href="https://downloader.caorushizi.cn/documents.html?form=github">文档</a>
|
||||
<span> • </span>
|
||||
<a href="https://github.com/caorushizi/mediago/discussions">Discussions</a>
|
||||
<br>
|
||||
|
||||
<a href="https://github.com/caorushizi/mediago/blob/master/README.md">English</a>
|
||||
<span> • </span>
|
||||
<a href="https://github.com/caorushizi/mediago/blob/master/README.jp.md">日本語</a>
|
||||
<br>
|
||||
|
||||
<!-- MediaGo Pro 推广 -->
|
||||
<a href="https://mediago.torchstellar.com/?from=github">
|
||||
<img src="https://img.shields.io/badge/✨_全新发布-MediaGo_Pro-ff6b6b?style=for-the-badge&logo=data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCAyNCAyNCIgZmlsbD0id2hpdGUiPjxwYXRoIGQ9Ik0xMiAyTDMgN2wzIDMgNi00IDYgNCAzLTMtOS01eiIvPjxwYXRoIGQ9Ik0zIDE3bDkgNSA5LTUtMy0zLTYgNC02LTQtMyAzeiIvPjwvc3ZnPg==" alt="MediaGo Pro" />
|
||||
</a>
|
||||
<a href="https://mediago.torchstellar.com/?from=github">
|
||||
<img src="https://img.shields.io/badge/🚀_立即体验-在线版本_无需安装-2a82f6?style=for-the-badge" alt="Try Now" />
|
||||
</a>
|
||||
<br>
|
||||
|
||||
<img alt="GitHub Downloads (all assets, all releases)" src="https://img.shields.io/github/downloads/caorushizi/mediago/total">
|
||||
<img alt="GitHub Downloads (all assets, latest release)" src="https://img.shields.io/github/downloads/caorushizi/mediago/latest/total">
|
||||
<img alt="GitHub Repo stars" src="https://img.shields.io/github/stars/caorushizi/mediago">
|
||||
<img alt="GitHub forks" src="https://img.shields.io/github/forks/caorushizi/mediago">
|
||||
<img alt="GitCode" src="https://gitcode.com/caorushizi/mediago/star/badge.svg">
|
||||
<br>
|
||||
|
||||
<a href="https://trendshift.io/repositories/11083" target="_blank">
|
||||
<img src="https://trendshift.io/api/badge/repositories/11083" alt="caorushizi%2Fmediago | Trendshift" style="width: 250px; height: 55px;" width="250" height="55"/>
|
||||
</a>
|
||||
|
||||
<hr />
|
||||
</div>
|
||||
|
||||
## Intro
|
||||
|
||||
本项目支持 m3u8 视频在线提取工具 流媒体下载 m3u8 下载。
|
||||
|
||||
- **✅ 无需抓包**: 使用软件自带浏览器可以轻松嗅探网页中的视频资源,通过嗅探到的资源列表选择自己想要下载的资源,简单快速。
|
||||
- **📱 移动播放**: 可以轻松无缝的在 PC 和移动设备之前切换,下载完成后即可使用手机观看视频。
|
||||
- **⚡️ 批量下载**: 支持同时下载多个视频和直播资源,高速带宽不闲置。
|
||||
- **🎉 支持 docker 部署**: 支持 docker 部署 web 端,方便快捷。
|
||||
- **🦞 OpenClaw Skill**: 支持通过 AI 编程助手(Openclaw、Claude Code 等)用自然语言下载视频,`npx clawhub@latest install mediago` 一键安装。
|
||||
|
||||
## Quickstart
|
||||
|
||||
运行代码需要 node 和 pnpm,node 需要在官网下载安装,pnpm 可以通过`npm i -g pnpm`安装。
|
||||
|
||||
## 运行代码
|
||||
|
||||
```shell
|
||||
# 代码下载
|
||||
git clone https://github.com/caorushizi/mediago.git
|
||||
|
||||
# 安装依赖
|
||||
pnpm install
|
||||
|
||||
# 首次安装需要 rebuild 一下
|
||||
pnpm rebuild:workspace
|
||||
|
||||
# electron 开发环境
|
||||
pnpm dev:electron
|
||||
|
||||
# electron 打包运行
|
||||
pnpm release:electron
|
||||
|
||||
# server 开发环境
|
||||
pnpm dev:server
|
||||
|
||||
# server 打包运行
|
||||
pnpm release:server
|
||||
|
||||
```
|
||||
|
||||
## Releases
|
||||
|
||||
### v3.5.0-beta.0 (2026.4.3 发布)
|
||||
|
||||
### 软件下载
|
||||
|
||||
- [【mediago】 windows(安装版) v3.5.0-beta.0](https://github.com/caorushizi/mediago/releases/download/v3.5.0-beta.0/mediago-community-setup-win32-x64-3.5.0-beta.0.exe)
|
||||
- [【mediago】 windows(便携版) v3.5.0-beta.0](https://github.com/caorushizi/mediago/releases/download/v3.5.0-beta.0/mediago-community-portable-win32-x64-3.5.0-beta.0.exe)
|
||||
- [【mediago】 macos arm64(apple 芯片) v3.5.0-beta.0](https://github.com/caorushizi/mediago/releases/download/v3.5.0-beta.0/mediago-community-setup-darwin-arm64-3.5.0-beta.0.dmg)
|
||||
- [【mediago】 macos x64(intel 芯片) v3.5.0-beta.0](https://github.com/caorushizi/mediago/releases/download/v3.5.0-beta.0/mediago-community-setup-darwin-x64-3.5.0-beta.0.dmg)
|
||||
- [【mediago】 linux v3.5.0-beta.0](https://github.com/caorushizi/mediago/releases/download/v3.5.0-beta.0/mediago-community-setup-linux-amd64-3.5.0-beta.0.deb)
|
||||
- 【mediago】 docker v3.0 `docker run -d --name mediago -p 8899:8899 -v /path/to/mediago:/app/mediago ghcr.io/caorushizi/mediago:3.5.0-beta.0`
|
||||
|
||||
### v3.0.0 (2024.10.7 发布)
|
||||
|
||||
#### 软件下载
|
||||
|
||||
- [【mediago】 windows(安装版) v3.0.0](https://github.com/caorushizi/mediago/releases/download/v3.0.0/mediago-setup-win32-x64-3.0.0.exe)
|
||||
- [【mediago】 windows(便携版) v3.0.0](https://github.com/caorushizi/mediago/releases/download/v3.0.0/mediago-portable-win32-x64-3.0.0.exe)
|
||||
- [【mediago】 macos arm64(apple 芯片) v3.0.0](https://github.com/caorushizi/mediago/releases/download/v3.0.0/mediago-setup-darwin-arm64-3.0.0.dmg)
|
||||
- [【mediago】 macos x64(intel 芯片) v3.0.0](https://github.com/caorushizi/mediago/releases/download/v3.0.0/mediago-setup-darwin-x64-3.0.0.dmg)
|
||||
- [【mediago】 linux v3.0.0](https://github.com/caorushizi/mediago/releases/download/v3.0.0/mediago-setup-linux-amd64-3.0.0.deb)
|
||||
- 【mediago】 docker `docker run -d --name mediago -p 8899:8899 -v /path/to/mediago:/app/mediago ghcr.io/caorushizi/mediago:latest`
|
||||
|
||||
### docker 宝塔面板一键部署(推荐)
|
||||
|
||||
1. 安装宝塔面板,前往 [宝塔面板](https://www.bt.cn/new/download.html?r=dk_mediago) 官网,选择正式版的脚本下载安装
|
||||
|
||||
2. 安装后登录宝塔面板,在菜单栏中点击 `Docker`,首次进入会提示安装`Docker`服务,点击立即安装,按提示完成安装
|
||||
|
||||
3. 安装完成后在应用商店中找到`MediaGo`,点击安装,配置域名等基本信息即可完成安装
|
||||
|
||||
### 软件截图
|
||||
|
||||

|
||||
|
||||
### 重要更新
|
||||
|
||||
- 支持 docker 部署 web 端
|
||||
- 更新桌面端 UI
|
||||
|
||||
### 更新日志
|
||||
|
||||
- 更新桌面端 UI
|
||||
- 支持 docker 部署 web 端
|
||||
- 新增视频播放,支持桌面端和移动端播放
|
||||
- 修复 mac 打开无法展示界面的问题
|
||||
- 优化了批量下载的交互
|
||||
- 添加了 windows 的便携版(免安装哦)
|
||||
- 优化了下载列表,支持页面中多个视频的嗅探
|
||||
- 支持收藏列表手动导入导出
|
||||
- 支持首页下载列表导出
|
||||
- 优化了【新建下载】表单的交互逻辑
|
||||
- 支持 UrlScheme 打开应用,并添加下载任务
|
||||
- 修复了一些 bug 并提升用户体验
|
||||
|
||||
## 软件截图
|
||||
|
||||

|
||||
|
||||

|
||||
|
||||

|
||||
|
||||

|
||||
|
||||
## 技术栈
|
||||
|
||||
- react <https://react.dev/>
|
||||
- electron <https://www.electronjs.org>
|
||||
- koa <https://koajs.com>
|
||||
- vite <https://cn.vitejs.dev>
|
||||
- antd <https://ant.design>
|
||||
- tailwindcss <https://tailwindcss.com>
|
||||
- shadcn <https://ui.shadcn.com/>
|
||||
- inversify <https://inversify.io>
|
||||
- typeorm <https://typeorm.io>
|
||||
|
||||
## 鸣谢
|
||||
|
||||
- N_m3u8DL-RE 来自于 <https://github.com/nilaoda/N_m3u8DL-RE>
|
||||
- BBDown 来自于 <https://github.com/nilaoda/BBDown>
|
||||
- mediago 来自于 <https://github.com/caorushizi/mediago-core>
|
||||
|
||||
## 免责声明
|
||||
|
||||
> **本项目仅供学习和研究使用,请勿用于任何商业或非法用途。**
|
||||
>
|
||||
> 1. 本项目提供的所有代码和功能仅作为学习流媒体技术的参考,使用者需自行遵守所在地区的法律法规。
|
||||
> 2. 使用本项目下载的任何内容,其版权归原始内容所有者所有。使用者应在下载后 24 小时内删除,或取得版权方授权。
|
||||
> 3. 本项目开发者不对使用者的任何行为承担责任,包括但不限于:下载受版权保护的内容、对第三方平台造成的影响等。
|
||||
> 4. 禁止将本项目用于大规模抓取、破坏平台服务或任何侵犯他人合法权益的行为。
|
||||
> 5. 使用本项目即表示您已阅读并同意本免责声明。如不同意,请立即停止使用并删除本项目。
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user