@hitch42/applet 0.1.1-beta.7 → 0.1.1-beta.9
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/_internal/client.js +120 -11
- package/dist/_internal/log-context.d.ts +34 -0
- package/dist/_internal/log-context.js +2 -0
- package/dist/_internal/server.d.ts +14 -1
- package/dist/_internal/server.js +122 -118
- package/dist/applet.js +22 -11
- package/dist/build-Bh_S5BUv.js +2 -0
- package/dist/{build-DauirTcY.js → build-CEfFoIZZ.js} +1 -1
- package/dist/{ci-gPrwo6C0.js → ci-BKw14X2h.js} +14 -13
- package/dist/client.d.ts +3 -3
- package/dist/{contract-DB9QQhD9.d.ts → contract-CsUpTBe0.d.ts} +1 -1
- package/dist/{deploy-CqrtNJ1x.js → deploy-wGYjwXrx.js} +139 -88
- package/dist/email-DBTVhNB_.js +62 -0
- package/dist/{generate-BIifT6PK.js → generate-BEIYs17x.js} +70 -32
- package/dist/generate-Dox-OYt6.js +2 -0
- package/dist/headers-DkNr9MLJ.js +17 -0
- package/dist/index.d.ts +122 -10
- package/dist/index.js +142 -26
- package/dist/{init-Wu6XmyVc.js → init-6oGPM46R.js} +15 -17
- package/dist/{load-config-BknBkdRs.js → load-config-xEdTXs0y.js} +2 -2
- package/dist/log-context-zu8U9Sjm.js +73 -0
- package/dist/{login-iT9MRuaw.js → login-CUx3TmFQ.js} +1 -1
- package/dist/{logs-B-qZGXSK.js → logs-DSjuEN0Q.js} +20 -22
- package/dist/{manifest-C489nYUy.d.ts → manifest-C6_F4bL8.d.ts} +7 -0
- package/dist/{manifest-Bd04cWhu.js → manifest-CJSL9GuC.js} +22 -3
- package/dist/me-BW7Paary.js +32 -0
- package/dist/{project-C_rtpjp8.js → project-BRZGd6xq.js} +202 -20
- package/dist/prompt-ChS-grYO.js +29 -0
- package/dist/query-cache-CXmAyLv3.js +82 -0
- package/dist/react.d.ts +3 -2
- package/dist/react.js +98 -80
- package/dist/schedules-C8_Svr4h.js +42 -0
- package/dist/server.d.ts +9 -4
- package/dist/server.js +29 -8
- package/dist/telephony-protocol-D-nf3Gca.d.ts +76 -0
- package/dist/telephony.d.ts +97 -0
- package/dist/telephony.js +726 -0
- package/dist/{upload-YbRKEqR6.d.ts → upload-DKZzz5kW.d.ts} +6 -6
- package/dist/{variables-DcwMeIau.js → variables-DT5RyHdH.js} +14 -39
- package/dist/vite.d.ts +3 -60
- package/dist/vite.js +497 -27
- package/dist/workflow-engine-BOTzURKM.js +111 -0
- package/dist/{workspace-B6lenAS5.js → workspace-D0dnnlxL.js} +37 -39
- package/package.json +18 -5
- package/scaffold/.agents/skills/hitch-applets/SKILL.md +50 -18
- package/scaffold/.agents/skills/hitch-applets/references/email-tracking.md +49 -0
- package/scaffold/.agents/skills/hitch-applets/references/files.md +3 -3
- package/scaffold/.agents/skills/hitch-applets/references/manifest.md +12 -2
- package/scaffold/.agents/skills/hitch-applets/references/markdown.md +2 -0
- package/scaffold/.agents/skills/hitch-applets/references/performance.md +1 -1
- package/scaffold/.agents/skills/hitch-applets/references/records.md +27 -4
- package/scaffold/.agents/skills/hitch-applets/references/schedules.md +7 -2
- package/scaffold/.agents/skills/hitch-applets/references/server.md +0 -3
- package/scaffold/.agents/skills/hitch-applets/references/workflows.md +11 -3
- package/scaffold/.agents/skills/hitch-cli/SKILL.md +20 -20
- package/scaffold/.agents/skills/hitch-data/SKILL.md +3 -2
- package/scaffold/.agents/skills/hitch-data/references/attributes.md +7 -1
- package/scaffold/.agents/skills/hitch-data/references/limits.md +23 -23
- package/scaffold/.agents/skills/hitch-theory/SKILL.md +151 -0
- package/scaffold/.agents/skills/react-best-practices/SKILL.md +127 -0
- package/scaffold/.agents/skills/react-best-practices/rules/advanced-effect-event-deps.md +50 -0
- package/scaffold/.agents/skills/react-best-practices/rules/advanced-event-handler-refs.md +55 -0
- package/scaffold/.agents/skills/react-best-practices/rules/advanced-init-once.md +42 -0
- package/scaffold/.agents/skills/react-best-practices/rules/advanced-use-latest.md +39 -0
- package/scaffold/.agents/skills/react-best-practices/rules/async-cheap-condition-before-await.md +37 -0
- package/scaffold/.agents/skills/react-best-practices/rules/async-defer-await.md +82 -0
- package/scaffold/.agents/skills/react-best-practices/rules/async-dependencies.md +48 -0
- package/scaffold/.agents/skills/react-best-practices/rules/async-parallel.md +24 -0
- package/scaffold/.agents/skills/react-best-practices/rules/bundle-analyzable-paths.md +42 -0
- package/scaffold/.agents/skills/react-best-practices/rules/bundle-barrel-imports.md +39 -0
- package/scaffold/.agents/skills/react-best-practices/rules/bundle-conditional.md +35 -0
- package/scaffold/.agents/skills/react-best-practices/rules/bundle-defer-third-party.md +46 -0
- package/scaffold/.agents/skills/react-best-practices/rules/bundle-dynamic-imports.md +38 -0
- package/scaffold/.agents/skills/react-best-practices/rules/bundle-preload.md +40 -0
- package/scaffold/.agents/skills/react-best-practices/rules/client-event-listeners.md +78 -0
- package/scaffold/.agents/skills/react-best-practices/rules/client-localstorage-schema.md +74 -0
- package/scaffold/.agents/skills/react-best-practices/rules/client-passive-event-listeners.md +48 -0
- package/scaffold/.agents/skills/react-best-practices/rules/js-batch-dom-css.md +110 -0
- package/scaffold/.agents/skills/react-best-practices/rules/js-cache-function-results.md +58 -0
- package/scaffold/.agents/skills/react-best-practices/rules/js-cache-property-access.md +28 -0
- package/scaffold/.agents/skills/react-best-practices/rules/js-cache-storage.md +56 -0
- package/scaffold/.agents/skills/react-best-practices/rules/js-combine-iterations.md +32 -0
- package/scaffold/.agents/skills/react-best-practices/rules/js-early-exit.md +50 -0
- package/scaffold/.agents/skills/react-best-practices/rules/js-flatmap-filter.md +51 -0
- package/scaffold/.agents/skills/react-best-practices/rules/js-hoist-regexp.md +45 -0
- package/scaffold/.agents/skills/react-best-practices/rules/js-index-maps.md +37 -0
- package/scaffold/.agents/skills/react-best-practices/rules/js-length-check-first.md +50 -0
- package/scaffold/.agents/skills/react-best-practices/rules/js-min-max-loop.md +82 -0
- package/scaffold/.agents/skills/react-best-practices/rules/js-request-idle-callback.md +104 -0
- package/scaffold/.agents/skills/react-best-practices/rules/js-set-map-lookups.md +24 -0
- package/scaffold/.agents/skills/react-best-practices/rules/js-tosorted-immutable.md +57 -0
- package/scaffold/.agents/skills/react-best-practices/rules/rendering-activity.md +26 -0
- package/scaffold/.agents/skills/react-best-practices/rules/rendering-animate-svg-wrapper.md +38 -0
- package/scaffold/.agents/skills/react-best-practices/rules/rendering-conditional-render.md +32 -0
- package/scaffold/.agents/skills/react-best-practices/rules/rendering-content-visibility.md +38 -0
- package/scaffold/.agents/skills/react-best-practices/rules/rendering-hoist-jsx.md +36 -0
- package/scaffold/.agents/skills/react-best-practices/rules/rendering-resource-hints.md +81 -0
- package/scaffold/.agents/skills/react-best-practices/rules/rendering-script-defer-async.md +36 -0
- package/scaffold/.agents/skills/react-best-practices/rules/rendering-svg-precision.md +28 -0
- package/scaffold/.agents/skills/react-best-practices/rules/rendering-usetransition-loading.md +43 -0
- package/scaffold/.agents/skills/react-best-practices/rules/rerender-defer-reads.md +39 -0
- package/scaffold/.agents/skills/react-best-practices/rules/rerender-dependencies.md +45 -0
- package/scaffold/.agents/skills/react-best-practices/rules/rerender-derived-state-no-effect.md +40 -0
- package/scaffold/.agents/skills/react-best-practices/rules/rerender-derived-state.md +29 -0
- package/scaffold/.agents/skills/react-best-practices/rules/rerender-functional-setstate.md +77 -0
- package/scaffold/.agents/skills/react-best-practices/rules/rerender-lazy-state-init.md +56 -0
- package/scaffold/.agents/skills/react-best-practices/rules/rerender-memo-with-default-value.md +36 -0
- package/scaffold/.agents/skills/react-best-practices/rules/rerender-memo.md +44 -0
- package/scaffold/.agents/skills/react-best-practices/rules/rerender-move-effect-to-event.md +45 -0
- package/scaffold/.agents/skills/react-best-practices/rules/rerender-no-inline-components.md +75 -0
- package/scaffold/.agents/skills/react-best-practices/rules/rerender-simple-expression-in-memo.md +35 -0
- package/scaffold/.agents/skills/react-best-practices/rules/rerender-split-combined-hooks.md +64 -0
- package/scaffold/.agents/skills/react-best-practices/rules/rerender-transitions.md +40 -0
- package/scaffold/.agents/skills/react-best-practices/rules/rerender-use-deferred-value.md +59 -0
- package/scaffold/.agents/skills/react-best-practices/rules/rerender-use-ref-transient-values.md +73 -0
- package/scaffold/.agents/skills/tanstack-query/SKILL.md +136 -0
- package/scaffold/.agents/skills/tanstack-query/references/compositions/automatic-invalidation-after-mutations.md +124 -0
- package/scaffold/.agents/skills/tanstack-query/references/compositions/broadcast-realtime-and-multi-tab-synchronization.md +150 -0
- package/scaffold/.agents/skills/tanstack-query/references/compositions/compose-query-with-tanstack-router-and-start.md +248 -0
- package/scaffold/.agents/skills/tanstack-query/references/compositions/enforce-query-best-practices-with-eslint.md +167 -0
- package/scaffold/.agents/skills/tanstack-query/references/compositions/persist-offline-and-restore-caches.md +181 -0
- package/scaffold/.agents/skills/tanstack-query/references/compositions/query-data-and-forms.md +156 -0
- package/scaffold/.agents/skills/tanstack-query/references/core/build-query-abstractions.md +130 -0
- package/scaffold/.agents/skills/tanstack-query/references/core/cancel-queries-and-consume-abort-signals.md +176 -0
- package/scaffold/.agents/skills/tanstack-query/references/core/concurrent-optimistic-updates.md +135 -0
- package/scaffold/.agents/skills/tanstack-query/references/core/coordinate-query-execution.md +188 -0
- package/scaffold/.agents/skills/tanstack-query/references/core/design-query-keys-and-options.md +182 -0
- package/scaffold/.agents/skills/tanstack-query/references/core/fetch-and-observe-queries.md +193 -0
- package/scaffold/.agents/skills/tanstack-query/references/core/implement-optimistic-updates-and-cache-writes.md +168 -0
- package/scaffold/.agents/skills/tanstack-query/references/core/paginate-and-build-infinite-queries.md +188 -0
- package/scaffold/.agents/skills/tanstack-query/references/core/seed-placeholder-select-and-transform-data.md +188 -0
- package/scaffold/.agents/skills/tanstack-query/references/core/selectors-and-derived-state.md +145 -0
- package/scaffold/.agents/skills/tanstack-query/references/core/tune-defaults-freshness-retries-and-refetching.md +172 -0
- package/scaffold/.agents/skills/tanstack-query/references/core/understand-query-internals-and-observers.md +104 -0
- package/scaffold/.agents/skills/tanstack-query/references/core/write-mutations-and-invalidate-related-queries.md +183 -0
- package/scaffold/.agents/skills/tanstack-query/references/framework/debug-with-devtools.md +169 -0
- package/scaffold/.agents/skills/tanstack-query/references/framework/handle-status-and-errors.md +119 -0
- package/scaffold/.agents/skills/tanstack-query/references/framework/shape-data-and-render-efficiently.md +184 -0
- package/scaffold/.agents/skills/tanstack-query/references/framework/use-framework-adapter-reactivity.md +185 -0
- package/scaffold/.agents/skills/tanstack-query/references/framework/use-suspense-and-error-boundaries.md +208 -0
- package/scaffold/.agents/skills/tanstack-query/references/lifecycle/migrate-major-versions-and-codemods.md +169 -0
- package/scaffold/.agents/skills/tanstack-query/references/lifecycle/prefetch-and-remove-request-waterfalls.md +228 -0
- package/scaffold/.agents/skills/tanstack-query/references/lifecycle/setup-query-client-and-providers.md +161 -0
- package/scaffold/.agents/skills/tanstack-query/references/lifecycle/ssr-hydration-and-streaming.md +209 -0
- package/scaffold/.agents/skills/tanstack-query/references/lifecycle/test-query-code.md +160 -0
- package/scaffold/.agents/skills/tanstack-router/SKILL.md +134 -0
- package/scaffold/.agents/skills/tanstack-router/references/compositions/router-query.md +412 -0
- package/scaffold/.agents/skills/tanstack-router/references/react-router.md +495 -0
- package/scaffold/.agents/skills/tanstack-router/references/router-core/auth-and-guards.md +495 -0
- package/scaffold/.agents/skills/tanstack-router/references/router-core/code-splitting.md +318 -0
- package/scaffold/.agents/skills/tanstack-router/references/router-core/data-loading.md +490 -0
- package/scaffold/.agents/skills/tanstack-router/references/router-core/index.md +158 -0
- package/scaffold/.agents/skills/tanstack-router/references/router-core/navigation.md +433 -0
- package/scaffold/.agents/skills/tanstack-router/references/router-core/not-found-and-errors.md +436 -0
- package/scaffold/.agents/skills/tanstack-router/references/router-core/path-params.md +383 -0
- package/scaffold/.agents/skills/tanstack-router/references/router-core/search-params.md +343 -0
- package/scaffold/.agents/skills/tanstack-router/references/router-core/ssr.md +462 -0
- package/scaffold/.agents/skills/tanstack-router/references/router-core/type-safety.md +493 -0
- package/scaffold/.agents/skills/tanstack-router/references/router-plugin.md +250 -0
- package/scaffold/.agents/skills/tanstack-router/references/virtual-file-routes.md +215 -0
- package/scaffold/.agents/skills/web-design-guidelines/SKILL.md +184 -0
- package/scaffold/.github/workflows/hitch.yml +1 -1
- package/scaffold/AGENTS.md +2 -2
- package/scaffold/applet/src/client/components/ui/alert.tsx +1 -1
- package/scaffold/applet/src/client/components/ui/button.tsx +1 -1
- package/scaffold/applet/src/client/components/ui/checkbox.tsx +1 -1
- package/scaffold/applet/src/client/components/ui/dialog.tsx +2 -2
- package/scaffold/applet/src/client/components/ui/dropdown-menu.tsx +2 -2
- package/scaffold/applet/src/client/components/ui/input-group.tsx +2 -2
- package/scaffold/applet/src/client/components/ui/select.tsx +2 -2
- package/scaffold/applet/src/client/components/ui/sheet.tsx +2 -2
- package/scaffold/applet/src/client/components/ui/spinner.tsx +2 -1
- package/scaffold/applet/src/client/components/ui/tabs.tsx +1 -1
- package/scaffold/applet/src/client/lib/utils.ts +1 -6
- package/scaffold/applet/src/client/styles/globals.css +2 -0
- package/dist/build-DhNDp7ji.js +0 -2
- package/dist/generate-DSk8ihsC.js +0 -2
|
@@ -0,0 +1,127 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: react-best-practices
|
|
3
|
+
description: Client React performance guidelines. Use when writing, reviewing, or refactoring React components, client data fetching, bundles, rendering, or browser performance.
|
|
4
|
+
license: MIT
|
|
5
|
+
metadata:
|
|
6
|
+
version: "1.0.0"
|
|
7
|
+
---
|
|
8
|
+
|
|
9
|
+
# React Best Practices
|
|
10
|
+
|
|
11
|
+
Performance guidance for client React applications. The rules focus on browser behavior, client data fetching, bundles, rendering, and re-renders.
|
|
12
|
+
|
|
13
|
+
## When to Apply
|
|
14
|
+
|
|
15
|
+
Reference these guidelines when:
|
|
16
|
+
|
|
17
|
+
- Writing new React components
|
|
18
|
+
- Implementing client data fetching
|
|
19
|
+
- Reviewing code for performance issues
|
|
20
|
+
- Refactoring existing React code
|
|
21
|
+
- Optimizing bundle size or load times
|
|
22
|
+
|
|
23
|
+
## Rule Categories by Priority
|
|
24
|
+
|
|
25
|
+
| Priority | Category | Impact | Prefix |
|
|
26
|
+
| -------- | ------------------------- | ----------- | ------------ |
|
|
27
|
+
| 1 | Eliminating Waterfalls | CRITICAL | `async-` |
|
|
28
|
+
| 2 | Bundle Size Optimization | CRITICAL | `bundle-` |
|
|
29
|
+
| 3 | Client-Side Data Fetching | MEDIUM-HIGH | `client-` |
|
|
30
|
+
| 4 | Re-render Optimization | MEDIUM | `rerender-` |
|
|
31
|
+
| 5 | Rendering Performance | MEDIUM | `rendering-` |
|
|
32
|
+
| 6 | JavaScript Performance | LOW-MEDIUM | `js-` |
|
|
33
|
+
| 7 | Advanced Patterns | LOW | `advanced-` |
|
|
34
|
+
|
|
35
|
+
## Quick Reference
|
|
36
|
+
|
|
37
|
+
### 1. Eliminating Waterfalls (CRITICAL)
|
|
38
|
+
|
|
39
|
+
- `async-cheap-condition-before-await` - Check cheap sync conditions before awaiting flags or remote values
|
|
40
|
+
- `async-defer-await` - Move await into branches where actually used
|
|
41
|
+
- `async-parallel` - Use Promise.all() for independent operations
|
|
42
|
+
- `async-dependencies` - Use better-all for partial dependencies
|
|
43
|
+
|
|
44
|
+
### 2. Bundle Size Optimization (CRITICAL)
|
|
45
|
+
|
|
46
|
+
- `bundle-barrel-imports` - Import directly, avoid barrel files
|
|
47
|
+
- `bundle-analyzable-paths` - Prefer statically analyzable imports
|
|
48
|
+
- `bundle-dynamic-imports` - Use React.lazy for heavy components
|
|
49
|
+
- `bundle-defer-third-party` - Split non-critical libraries from the initial bundle
|
|
50
|
+
- `bundle-conditional` - Load modules only when feature is activated
|
|
51
|
+
- `bundle-preload` - Preload on hover/focus for perceived speed
|
|
52
|
+
|
|
53
|
+
### 3. Client-Side Data Fetching (MEDIUM-HIGH)
|
|
54
|
+
|
|
55
|
+
- `client-event-listeners` - Deduplicate global event listeners
|
|
56
|
+
- `client-passive-event-listeners` - Use passive listeners for scroll
|
|
57
|
+
- `client-localstorage-schema` - Version and minimize localStorage data
|
|
58
|
+
|
|
59
|
+
### 4. Re-render Optimization (MEDIUM)
|
|
60
|
+
|
|
61
|
+
- `rerender-defer-reads` - Don't subscribe to state only used in callbacks
|
|
62
|
+
- `rerender-memo` - Extract expensive work into memoized components
|
|
63
|
+
- `rerender-memo-with-default-value` - Hoist default non-primitive props
|
|
64
|
+
- `rerender-dependencies` - Use primitive dependencies in effects
|
|
65
|
+
- `rerender-derived-state` - Subscribe to derived booleans, not raw values
|
|
66
|
+
- `rerender-derived-state-no-effect` - Derive state during render, not effects
|
|
67
|
+
- `rerender-functional-setstate` - Use functional setState for stable callbacks
|
|
68
|
+
- `rerender-lazy-state-init` - Pass function to useState for expensive values
|
|
69
|
+
- `rerender-simple-expression-in-memo` - Avoid memo for simple primitives
|
|
70
|
+
- `rerender-split-combined-hooks` - Split hooks with independent dependencies
|
|
71
|
+
- `rerender-move-effect-to-event` - Put interaction logic in event handlers
|
|
72
|
+
- `rerender-transitions` - Use startTransition for non-urgent updates
|
|
73
|
+
- `rerender-use-deferred-value` - Defer expensive renders to keep input responsive
|
|
74
|
+
- `rerender-use-ref-transient-values` - Use refs for transient frequent values
|
|
75
|
+
- `rerender-no-inline-components` - Don't define components inside components
|
|
76
|
+
|
|
77
|
+
### 5. Rendering Performance (MEDIUM)
|
|
78
|
+
|
|
79
|
+
- `rendering-animate-svg-wrapper` - Animate div wrapper, not SVG element
|
|
80
|
+
- `rendering-content-visibility` - Use content-visibility for long lists
|
|
81
|
+
- `rendering-hoist-jsx` - Extract static JSX outside components
|
|
82
|
+
- `rendering-svg-precision` - Reduce SVG coordinate precision
|
|
83
|
+
- `rendering-activity` - Use Activity component for show/hide
|
|
84
|
+
- `rendering-conditional-render` - Use ternary, not && for conditionals
|
|
85
|
+
- `rendering-usetransition-loading` - Track async action pending state with useTransition
|
|
86
|
+
- `rendering-resource-hints` - Use React DOM resource hints for preloading
|
|
87
|
+
- `rendering-script-defer-async` - Use defer or async on script tags
|
|
88
|
+
|
|
89
|
+
### 6. JavaScript Performance (LOW-MEDIUM)
|
|
90
|
+
|
|
91
|
+
- `js-batch-dom-css` - Group CSS changes via classes or cssText
|
|
92
|
+
- `js-index-maps` - Build Map for repeated lookups
|
|
93
|
+
- `js-cache-property-access` - Cache object properties in loops
|
|
94
|
+
- `js-cache-function-results` - Cache function results in module-level Map
|
|
95
|
+
- `js-cache-storage` - Cache localStorage/sessionStorage reads
|
|
96
|
+
- `js-combine-iterations` - Combine multiple filter/map into one loop
|
|
97
|
+
- `js-length-check-first` - Check array length before expensive comparison
|
|
98
|
+
- `js-early-exit` - Return early from functions
|
|
99
|
+
- `js-hoist-regexp` - Hoist RegExp creation outside loops
|
|
100
|
+
- `js-min-max-loop` - Use loop for min/max instead of sort
|
|
101
|
+
- `js-set-map-lookups` - Use Set/Map for O(1) lookups
|
|
102
|
+
- `js-tosorted-immutable` - Use toSorted() for immutability
|
|
103
|
+
- `js-flatmap-filter` - Use flatMap to map and filter in one pass
|
|
104
|
+
- `js-request-idle-callback` - Defer non-critical work to browser idle time
|
|
105
|
+
|
|
106
|
+
### 7. Advanced Patterns (LOW)
|
|
107
|
+
|
|
108
|
+
- `advanced-effect-event-deps` - Don't put `useEffectEvent` results in effect deps
|
|
109
|
+
- `advanced-event-handler-refs` - Store event handlers in refs
|
|
110
|
+
- `advanced-init-once` - Initialize app once per app load
|
|
111
|
+
- `advanced-use-latest` - useLatest for stable callback refs
|
|
112
|
+
|
|
113
|
+
## How to Use
|
|
114
|
+
|
|
115
|
+
Read individual rule files for detailed explanations and code examples:
|
|
116
|
+
|
|
117
|
+
```
|
|
118
|
+
rules/async-parallel.md
|
|
119
|
+
rules/bundle-barrel-imports.md
|
|
120
|
+
```
|
|
121
|
+
|
|
122
|
+
Each rule file contains:
|
|
123
|
+
|
|
124
|
+
- Brief explanation of why it matters
|
|
125
|
+
- Incorrect code example with explanation
|
|
126
|
+
- Correct code example with explanation
|
|
127
|
+
- Additional context and references
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
---
|
|
2
|
+
title: Do Not Put Effect Events in Dependency Arrays
|
|
3
|
+
impact: LOW
|
|
4
|
+
impactDescription: avoids unnecessary effect re-runs and lint errors
|
|
5
|
+
tags: advanced, hooks, useEffectEvent, dependencies, effects
|
|
6
|
+
---
|
|
7
|
+
|
|
8
|
+
## Do Not Put Effect Events in Dependency Arrays
|
|
9
|
+
|
|
10
|
+
Effect Event functions do not have a stable identity. Their identity intentionally changes on every render. Do not include the function returned by `useEffectEvent` in a `useEffect` dependency array. Keep the actual reactive values as dependencies and call the Effect Event from inside the effect body or subscriptions created by that effect.
|
|
11
|
+
|
|
12
|
+
**Incorrect (Effect Event added as a dependency):**
|
|
13
|
+
|
|
14
|
+
```tsx
|
|
15
|
+
import { useEffect, useEffectEvent } from "react";
|
|
16
|
+
|
|
17
|
+
function ChatRoom({ roomId, onConnected }: { roomId: string; onConnected: () => void }) {
|
|
18
|
+
const handleConnected = useEffectEvent(onConnected);
|
|
19
|
+
|
|
20
|
+
useEffect(() => {
|
|
21
|
+
const connection = createConnection(roomId);
|
|
22
|
+
connection.on("connected", handleConnected);
|
|
23
|
+
connection.connect();
|
|
24
|
+
|
|
25
|
+
return () => connection.disconnect();
|
|
26
|
+
}, [roomId, handleConnected]);
|
|
27
|
+
}
|
|
28
|
+
```
|
|
29
|
+
|
|
30
|
+
Including the Effect Event in dependencies makes the effect re-run every render and triggers the React Hooks lint rule.
|
|
31
|
+
|
|
32
|
+
**Correct (depend on reactive values, not the Effect Event):**
|
|
33
|
+
|
|
34
|
+
```tsx
|
|
35
|
+
import { useEffect, useEffectEvent } from "react";
|
|
36
|
+
|
|
37
|
+
function ChatRoom({ roomId, onConnected }: { roomId: string; onConnected: () => void }) {
|
|
38
|
+
const handleConnected = useEffectEvent(onConnected);
|
|
39
|
+
|
|
40
|
+
useEffect(() => {
|
|
41
|
+
const connection = createConnection(roomId);
|
|
42
|
+
connection.on("connected", handleConnected);
|
|
43
|
+
connection.connect();
|
|
44
|
+
|
|
45
|
+
return () => connection.disconnect();
|
|
46
|
+
}, [roomId]);
|
|
47
|
+
}
|
|
48
|
+
```
|
|
49
|
+
|
|
50
|
+
Reference: [React useEffectEvent: Effect Event in deps](https://react.dev/reference/react/useEffectEvent#effect-event-in-deps)
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
---
|
|
2
|
+
title: Store Event Handlers in Refs
|
|
3
|
+
impact: LOW
|
|
4
|
+
impactDescription: stable subscriptions
|
|
5
|
+
tags: advanced, hooks, refs, event-handlers, optimization
|
|
6
|
+
---
|
|
7
|
+
|
|
8
|
+
## Store Event Handlers in Refs
|
|
9
|
+
|
|
10
|
+
Store callbacks in refs when used in effects that shouldn't re-subscribe on callback changes.
|
|
11
|
+
|
|
12
|
+
**Incorrect (re-subscribes on every render):**
|
|
13
|
+
|
|
14
|
+
```tsx
|
|
15
|
+
function useWindowEvent(event: string, handler: (e) => void) {
|
|
16
|
+
useEffect(() => {
|
|
17
|
+
window.addEventListener(event, handler);
|
|
18
|
+
return () => window.removeEventListener(event, handler);
|
|
19
|
+
}, [event, handler]);
|
|
20
|
+
}
|
|
21
|
+
```
|
|
22
|
+
|
|
23
|
+
**Correct (stable subscription):**
|
|
24
|
+
|
|
25
|
+
```tsx
|
|
26
|
+
function useWindowEvent(event: string, handler: (e) => void) {
|
|
27
|
+
const handlerRef = useRef(handler);
|
|
28
|
+
useEffect(() => {
|
|
29
|
+
handlerRef.current = handler;
|
|
30
|
+
}, [handler]);
|
|
31
|
+
|
|
32
|
+
useEffect(() => {
|
|
33
|
+
const listener = (e) => handlerRef.current(e);
|
|
34
|
+
window.addEventListener(event, listener);
|
|
35
|
+
return () => window.removeEventListener(event, listener);
|
|
36
|
+
}, [event]);
|
|
37
|
+
}
|
|
38
|
+
```
|
|
39
|
+
|
|
40
|
+
**Alternative: use `useEffectEvent` if you're on latest React:**
|
|
41
|
+
|
|
42
|
+
```tsx
|
|
43
|
+
import { useEffectEvent } from "react";
|
|
44
|
+
|
|
45
|
+
function useWindowEvent(event: string, handler: (e) => void) {
|
|
46
|
+
const onEvent = useEffectEvent(handler);
|
|
47
|
+
|
|
48
|
+
useEffect(() => {
|
|
49
|
+
window.addEventListener(event, onEvent);
|
|
50
|
+
return () => window.removeEventListener(event, onEvent);
|
|
51
|
+
}, [event]);
|
|
52
|
+
}
|
|
53
|
+
```
|
|
54
|
+
|
|
55
|
+
`useEffectEvent` reads the latest handler without re-subscribing. The Effect Event function does not have a stable identity.
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
---
|
|
2
|
+
title: Initialize App Once, Not Per Mount
|
|
3
|
+
impact: LOW-MEDIUM
|
|
4
|
+
impactDescription: avoids duplicate init in development
|
|
5
|
+
tags: initialization, useEffect, app-startup, side-effects
|
|
6
|
+
---
|
|
7
|
+
|
|
8
|
+
## Initialize App Once, Not Per Mount
|
|
9
|
+
|
|
10
|
+
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.
|
|
11
|
+
|
|
12
|
+
**Incorrect (runs twice in dev, re-runs on remount):**
|
|
13
|
+
|
|
14
|
+
```tsx
|
|
15
|
+
function Comp() {
|
|
16
|
+
useEffect(() => {
|
|
17
|
+
loadFromStorage();
|
|
18
|
+
checkAuthToken();
|
|
19
|
+
}, []);
|
|
20
|
+
|
|
21
|
+
// ...
|
|
22
|
+
}
|
|
23
|
+
```
|
|
24
|
+
|
|
25
|
+
**Correct (once per app load):**
|
|
26
|
+
|
|
27
|
+
```tsx
|
|
28
|
+
let didInit = false;
|
|
29
|
+
|
|
30
|
+
function Comp() {
|
|
31
|
+
useEffect(() => {
|
|
32
|
+
if (didInit) return;
|
|
33
|
+
didInit = true;
|
|
34
|
+
loadFromStorage();
|
|
35
|
+
checkAuthToken();
|
|
36
|
+
}, []);
|
|
37
|
+
|
|
38
|
+
// ...
|
|
39
|
+
}
|
|
40
|
+
```
|
|
41
|
+
|
|
42
|
+
Reference: [Initializing the application](https://react.dev/learn/you-might-not-need-an-effect#initializing-the-application)
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
---
|
|
2
|
+
title: useEffectEvent for Stable Callback Refs
|
|
3
|
+
impact: LOW
|
|
4
|
+
impactDescription: prevents effect re-runs
|
|
5
|
+
tags: advanced, hooks, useEffectEvent, refs, optimization
|
|
6
|
+
---
|
|
7
|
+
|
|
8
|
+
## useEffectEvent for Stable Callback Refs
|
|
9
|
+
|
|
10
|
+
Access latest values in callbacks without adding them to dependency arrays. Prevents effect re-runs while avoiding stale closures.
|
|
11
|
+
|
|
12
|
+
**Incorrect (effect re-runs on every callback change):**
|
|
13
|
+
|
|
14
|
+
```tsx
|
|
15
|
+
function SearchInput({ onSearch }: { onSearch: (q: string) => void }) {
|
|
16
|
+
const [query, setQuery] = useState("");
|
|
17
|
+
|
|
18
|
+
useEffect(() => {
|
|
19
|
+
const timeout = setTimeout(() => onSearch(query), 300);
|
|
20
|
+
return () => clearTimeout(timeout);
|
|
21
|
+
}, [query, onSearch]);
|
|
22
|
+
}
|
|
23
|
+
```
|
|
24
|
+
|
|
25
|
+
**Correct (using React's useEffectEvent):**
|
|
26
|
+
|
|
27
|
+
```tsx
|
|
28
|
+
import { useEffectEvent } from "react";
|
|
29
|
+
|
|
30
|
+
function SearchInput({ onSearch }: { onSearch: (q: string) => void }) {
|
|
31
|
+
const [query, setQuery] = useState("");
|
|
32
|
+
const onSearchEvent = useEffectEvent(onSearch);
|
|
33
|
+
|
|
34
|
+
useEffect(() => {
|
|
35
|
+
const timeout = setTimeout(() => onSearchEvent(query), 300);
|
|
36
|
+
return () => clearTimeout(timeout);
|
|
37
|
+
}, [query]);
|
|
38
|
+
}
|
|
39
|
+
```
|
package/scaffold/.agents/skills/react-best-practices/rules/async-cheap-condition-before-await.md
ADDED
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
---
|
|
2
|
+
title: Check Cheap Conditions Before Async Flags
|
|
3
|
+
impact: HIGH
|
|
4
|
+
impactDescription: avoids unnecessary async work when a synchronous guard already fails
|
|
5
|
+
tags: async, await, feature-flags, short-circuit, conditional
|
|
6
|
+
---
|
|
7
|
+
|
|
8
|
+
## Check Cheap Conditions Before Async Flags
|
|
9
|
+
|
|
10
|
+
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.
|
|
11
|
+
|
|
12
|
+
This is a specialization of [Defer Await Until Needed](./async-defer-await.md) for `flag && cheapCondition` style checks.
|
|
13
|
+
|
|
14
|
+
**Incorrect:**
|
|
15
|
+
|
|
16
|
+
```typescript
|
|
17
|
+
const someFlag = await getFlag();
|
|
18
|
+
|
|
19
|
+
if (someFlag && someCondition) {
|
|
20
|
+
// ...
|
|
21
|
+
}
|
|
22
|
+
```
|
|
23
|
+
|
|
24
|
+
**Correct:**
|
|
25
|
+
|
|
26
|
+
```typescript
|
|
27
|
+
if (someCondition) {
|
|
28
|
+
const someFlag = await getFlag();
|
|
29
|
+
if (someFlag) {
|
|
30
|
+
// ...
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
```
|
|
34
|
+
|
|
35
|
+
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.
|
|
36
|
+
|
|
37
|
+
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 @@
|
|
|
1
|
+
---
|
|
2
|
+
title: Defer Await Until Needed
|
|
3
|
+
impact: HIGH
|
|
4
|
+
impactDescription: avoids blocking unused code paths
|
|
5
|
+
tags: async, await, conditional, optimization
|
|
6
|
+
---
|
|
7
|
+
|
|
8
|
+
## Defer Await Until Needed
|
|
9
|
+
|
|
10
|
+
Move `await` operations into the branches where they're actually used to avoid blocking code paths that don't need them.
|
|
11
|
+
|
|
12
|
+
**Incorrect (blocks both branches):**
|
|
13
|
+
|
|
14
|
+
```typescript
|
|
15
|
+
async function handleRequest(userId: string, skipProcessing: boolean) {
|
|
16
|
+
const userData = await fetchUserData(userId);
|
|
17
|
+
|
|
18
|
+
if (skipProcessing) {
|
|
19
|
+
// Returns immediately but still waited for userData
|
|
20
|
+
return { skipped: true };
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
// Only this branch uses userData
|
|
24
|
+
return processUserData(userData);
|
|
25
|
+
}
|
|
26
|
+
```
|
|
27
|
+
|
|
28
|
+
**Correct (only blocks when needed):**
|
|
29
|
+
|
|
30
|
+
```typescript
|
|
31
|
+
async function handleRequest(userId: string, skipProcessing: boolean) {
|
|
32
|
+
if (skipProcessing) {
|
|
33
|
+
// Returns immediately without waiting
|
|
34
|
+
return { skipped: true };
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
// Fetch only when needed
|
|
38
|
+
const userData = await fetchUserData(userId);
|
|
39
|
+
return processUserData(userData);
|
|
40
|
+
}
|
|
41
|
+
```
|
|
42
|
+
|
|
43
|
+
**Another example (early return optimization):**
|
|
44
|
+
|
|
45
|
+
```typescript
|
|
46
|
+
// Incorrect: always fetches permissions
|
|
47
|
+
async function updateResource(resourceId: string, userId: string) {
|
|
48
|
+
const permissions = await fetchPermissions(userId);
|
|
49
|
+
const resource = await getResource(resourceId);
|
|
50
|
+
|
|
51
|
+
if (!resource) {
|
|
52
|
+
return { error: "Not found" };
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
if (!permissions.canEdit) {
|
|
56
|
+
return { error: "Forbidden" };
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
return await updateResourceData(resource, permissions);
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
// Correct: fetches only when needed
|
|
63
|
+
async function updateResource(resourceId: string, userId: string) {
|
|
64
|
+
const resource = await getResource(resourceId);
|
|
65
|
+
|
|
66
|
+
if (!resource) {
|
|
67
|
+
return { error: "Not found" };
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
const permissions = await fetchPermissions(userId);
|
|
71
|
+
|
|
72
|
+
if (!permissions.canEdit) {
|
|
73
|
+
return { error: "Forbidden" };
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
return await updateResourceData(resource, permissions);
|
|
77
|
+
}
|
|
78
|
+
```
|
|
79
|
+
|
|
80
|
+
This optimization is especially valuable when the skipped branch is frequently taken, or when the deferred operation is expensive.
|
|
81
|
+
|
|
82
|
+
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,48 @@
|
|
|
1
|
+
---
|
|
2
|
+
title: Dependency-Based Parallelization
|
|
3
|
+
impact: CRITICAL
|
|
4
|
+
impactDescription: 2-10× improvement
|
|
5
|
+
tags: async, parallelization, dependencies, better-all
|
|
6
|
+
---
|
|
7
|
+
|
|
8
|
+
## Dependency-Based Parallelization
|
|
9
|
+
|
|
10
|
+
For operations with partial dependencies, use `better-all` to maximize parallelism. It automatically starts each task at the earliest possible moment.
|
|
11
|
+
|
|
12
|
+
**Incorrect (profile waits for config unnecessarily):**
|
|
13
|
+
|
|
14
|
+
```typescript
|
|
15
|
+
const [user, config] = await Promise.all([fetchUser(), fetchConfig()]);
|
|
16
|
+
const profile = await fetchProfile(user.id);
|
|
17
|
+
```
|
|
18
|
+
|
|
19
|
+
**Correct (config and profile run in parallel):**
|
|
20
|
+
|
|
21
|
+
```typescript
|
|
22
|
+
import { all } from "better-all";
|
|
23
|
+
|
|
24
|
+
const { user, config, profile } = await all({
|
|
25
|
+
async user() {
|
|
26
|
+
return fetchUser();
|
|
27
|
+
},
|
|
28
|
+
async config() {
|
|
29
|
+
return fetchConfig();
|
|
30
|
+
},
|
|
31
|
+
async profile() {
|
|
32
|
+
return fetchProfile((await this.$.user).id);
|
|
33
|
+
},
|
|
34
|
+
});
|
|
35
|
+
```
|
|
36
|
+
|
|
37
|
+
**Alternative without extra dependencies:**
|
|
38
|
+
|
|
39
|
+
We can also create all the promises first, and do `Promise.all()` at the end.
|
|
40
|
+
|
|
41
|
+
```typescript
|
|
42
|
+
const userPromise = fetchUser();
|
|
43
|
+
const profilePromise = userPromise.then((user) => fetchProfile(user.id));
|
|
44
|
+
|
|
45
|
+
const [user, config, profile] = await Promise.all([userPromise, fetchConfig(), profilePromise]);
|
|
46
|
+
```
|
|
47
|
+
|
|
48
|
+
Reference: [https://github.com/shuding/better-all](https://github.com/shuding/better-all)
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
---
|
|
2
|
+
title: Promise.all() for Independent Operations
|
|
3
|
+
impact: CRITICAL
|
|
4
|
+
impactDescription: 2-10× improvement
|
|
5
|
+
tags: async, parallelization, promises, waterfalls
|
|
6
|
+
---
|
|
7
|
+
|
|
8
|
+
## Promise.all() for Independent Operations
|
|
9
|
+
|
|
10
|
+
When async operations have no interdependencies, execute them concurrently using `Promise.all()`.
|
|
11
|
+
|
|
12
|
+
**Incorrect (sequential execution, 3 round trips):**
|
|
13
|
+
|
|
14
|
+
```typescript
|
|
15
|
+
const user = await fetchUser();
|
|
16
|
+
const posts = await fetchPosts();
|
|
17
|
+
const comments = await fetchComments();
|
|
18
|
+
```
|
|
19
|
+
|
|
20
|
+
**Correct (parallel execution, 1 round trip):**
|
|
21
|
+
|
|
22
|
+
```typescript
|
|
23
|
+
const [user, posts, comments] = await Promise.all([fetchUser(), fetchPosts(), fetchComments()]);
|
|
24
|
+
```
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
---
|
|
2
|
+
title: Prefer Statically Analyzable Imports
|
|
3
|
+
impact: HIGH
|
|
4
|
+
impactDescription: avoids accidental broad bundles and file traces
|
|
5
|
+
tags: bundle, vite, webpack, rollup, esbuild, imports
|
|
6
|
+
---
|
|
7
|
+
|
|
8
|
+
## Prefer Statically Analyzable Imports
|
|
9
|
+
|
|
10
|
+
Build tools work best when import paths are obvious at build time. If you hide the real path inside a variable, the tool can include too many files or fail to split the bundle correctly.
|
|
11
|
+
|
|
12
|
+
Prefer explicit maps or literal paths so the set of reachable modules stays narrow and predictable.
|
|
13
|
+
|
|
14
|
+
When analysis becomes too broad, the cost is real:
|
|
15
|
+
|
|
16
|
+
- Larger browser bundles
|
|
17
|
+
- Slower builds
|
|
18
|
+
- More memory use
|
|
19
|
+
|
|
20
|
+
**Incorrect (the bundler cannot tell what may be imported):**
|
|
21
|
+
|
|
22
|
+
```ts
|
|
23
|
+
const PAGE_MODULES = {
|
|
24
|
+
home: "./pages/home",
|
|
25
|
+
settings: "./pages/settings",
|
|
26
|
+
} as const;
|
|
27
|
+
|
|
28
|
+
const Page = await import(PAGE_MODULES[pageName]);
|
|
29
|
+
```
|
|
30
|
+
|
|
31
|
+
**Correct (use an explicit map of allowed modules):**
|
|
32
|
+
|
|
33
|
+
```ts
|
|
34
|
+
const PAGE_MODULES = {
|
|
35
|
+
home: () => import("./pages/home"),
|
|
36
|
+
settings: () => import("./pages/settings"),
|
|
37
|
+
} as const;
|
|
38
|
+
|
|
39
|
+
const Page = await PAGE_MODULES[pageName]();
|
|
40
|
+
```
|
|
41
|
+
|
|
42
|
+
Reference: [Vite features](https://vite.dev/guide/features.html), [esbuild API](https://esbuild.github.io/api/), [Rollup dynamic import vars](https://www.npmjs.com/package/@rollup/plugin-dynamic-import-vars), [Webpack dependency management](https://webpack.js.org/guides/dependency-management/)
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
---
|
|
2
|
+
title: Avoid Barrel File Imports
|
|
3
|
+
impact: CRITICAL
|
|
4
|
+
impactDescription: 200-800ms import cost, slow builds
|
|
5
|
+
tags: bundle, imports, tree-shaking, barrel-files, performance
|
|
6
|
+
---
|
|
7
|
+
|
|
8
|
+
## Avoid Barrel File Imports
|
|
9
|
+
|
|
10
|
+
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'`).
|
|
11
|
+
|
|
12
|
+
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.
|
|
13
|
+
|
|
14
|
+
**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.
|
|
15
|
+
|
|
16
|
+
**Incorrect (imports entire library):**
|
|
17
|
+
|
|
18
|
+
```tsx
|
|
19
|
+
import { Check, X, Menu } from "lucide-react";
|
|
20
|
+
// Loads 1,583 modules, takes ~2.8s extra in dev
|
|
21
|
+
// Runtime cost: 200-800ms on every cold start
|
|
22
|
+
|
|
23
|
+
import { Button, TextField } from "@mui/material";
|
|
24
|
+
// Loads 2,225 modules, takes ~4.2s extra in dev
|
|
25
|
+
```
|
|
26
|
+
|
|
27
|
+
**Correct (direct imports):**
|
|
28
|
+
|
|
29
|
+
```tsx
|
|
30
|
+
import Button from "@mui/material/Button";
|
|
31
|
+
import TextField from "@mui/material/TextField";
|
|
32
|
+
// Loads only what you use
|
|
33
|
+
```
|
|
34
|
+
|
|
35
|
+
> **TypeScript warning:** Some libraries do not publish types for deep import paths. Verify that the package exports types for each subpath.
|
|
36
|
+
|
|
37
|
+
These imports reduce the modules that the browser and build tool must process.
|
|
38
|
+
|
|
39
|
+
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`.
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
---
|
|
2
|
+
title: Conditional Module Loading
|
|
3
|
+
impact: HIGH
|
|
4
|
+
impactDescription: loads large data only when needed
|
|
5
|
+
tags: bundle, conditional-loading, lazy-loading
|
|
6
|
+
---
|
|
7
|
+
|
|
8
|
+
## Conditional Module Loading
|
|
9
|
+
|
|
10
|
+
Load large data or modules only when a feature is activated.
|
|
11
|
+
|
|
12
|
+
**Example (lazy-load animation frames):**
|
|
13
|
+
|
|
14
|
+
```tsx
|
|
15
|
+
function AnimationPlayer({
|
|
16
|
+
enabled,
|
|
17
|
+
setEnabled,
|
|
18
|
+
}: {
|
|
19
|
+
enabled: boolean;
|
|
20
|
+
setEnabled: React.Dispatch<React.SetStateAction<boolean>>;
|
|
21
|
+
}) {
|
|
22
|
+
const [frames, setFrames] = useState<Frame[] | null>(null);
|
|
23
|
+
|
|
24
|
+
useEffect(() => {
|
|
25
|
+
if (enabled && !frames) {
|
|
26
|
+
import("./animation-frames.js")
|
|
27
|
+
.then((mod) => setFrames(mod.frames))
|
|
28
|
+
.catch(() => setEnabled(false));
|
|
29
|
+
}
|
|
30
|
+
}, [enabled, frames, setEnabled]);
|
|
31
|
+
|
|
32
|
+
if (!frames) return <Skeleton />;
|
|
33
|
+
return <Canvas frames={frames} />;
|
|
34
|
+
}
|
|
35
|
+
```
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
---
|
|
2
|
+
title: Defer Non-Critical Third-Party Libraries
|
|
3
|
+
impact: MEDIUM
|
|
4
|
+
impactDescription: reduces the initial bundle
|
|
5
|
+
tags: bundle, third-party, analytics, defer
|
|
6
|
+
---
|
|
7
|
+
|
|
8
|
+
## Defer Non-Critical Third-Party Libraries
|
|
9
|
+
|
|
10
|
+
Some analytics and logging components do not need to be in the initial bundle. Load them in a separate chunk.
|
|
11
|
+
|
|
12
|
+
**Incorrect (blocks initial bundle):**
|
|
13
|
+
|
|
14
|
+
```tsx
|
|
15
|
+
import Analytics from "./analytics";
|
|
16
|
+
|
|
17
|
+
export default function App() {
|
|
18
|
+
return (
|
|
19
|
+
<>
|
|
20
|
+
<AppRoutes />
|
|
21
|
+
<Analytics />
|
|
22
|
+
</>
|
|
23
|
+
);
|
|
24
|
+
}
|
|
25
|
+
```
|
|
26
|
+
|
|
27
|
+
**Correct (loads from a separate chunk):**
|
|
28
|
+
|
|
29
|
+
```tsx
|
|
30
|
+
import { lazy, Suspense } from "react";
|
|
31
|
+
|
|
32
|
+
const Analytics = lazy(() => import("./analytics"));
|
|
33
|
+
|
|
34
|
+
export default function App() {
|
|
35
|
+
return (
|
|
36
|
+
<>
|
|
37
|
+
<AppRoutes />
|
|
38
|
+
<Suspense fallback={null}>
|
|
39
|
+
<Analytics />
|
|
40
|
+
</Suspense>
|
|
41
|
+
</>
|
|
42
|
+
);
|
|
43
|
+
}
|
|
44
|
+
```
|
|
45
|
+
|
|
46
|
+
`React.lazy` loads this chunk when React first renders `<Analytics>`. This example renders it on startup, so it does not wait for idle time.
|