返回 Skills
software-mansion/argent· Apache-2.0 内容可用

argent-react-native-optimization

Optimizes a React Native app by profiling first to find real bottlenecks, then sweeping for mechanical issues. Entry-point for all performance work. Use when the app feels slow, user asks to optimize, fix re-renders, reduce jank, or improve startup. Delegates to argent-react-native-profiler for measurement.

安装

与 skills.sh 相同的 Command / Prompt 安装方式


name: argent-react-native-optimization description: Optimizes a React Native app by profiling first to find real bottlenecks, then sweeping for mechanical issues. Entry-point for all performance work. Use when the app feels slow, user asks to optimize, fix re-renders, reduce jank, or improve startup. Delegates to argent-react-native-profiler for measurement.

Rules

  • Do not apply shotgun optimizations. Measure first, define what "good enough" looks like (target metric + threshold), fix the top offender, re-measure honestly.
  • Quick scanreact-profiler-renders for a live render count table. Identifies hot components instantly.
  • Deep measure — load argent-react-native-profiler skill. react-profiler-start → interact → react-profiler-stopreact-profiler-analyze.
  • Inspectreact-profiler-component-source per finding. react-profiler-fiber-tree to trace component ancestry and render cost.
  • Verify correctness - before fixing, recollect information from steps above and make a logical conclusion whether the approach is worth undertaking.
  • Fix — apply one fix. Validate with debugger-evaluate before committing.
  • Re-measure — report whether the target metric improved, regressed, or stayed flat. Check for regressions in other areas. If no net benefit or unacceptable tradeoffs, revert.
  • Profile for discovery, not only verification. Use the profiler to find issues static analysis missed, not only to confirm fixes.
  • One fix per cycle for architectural changes. Mechanical batch fixes (inline styles, index keys) can be grouped — re-profile once after the batch. When the measurement involves device interaction, record it as a flow (argent-create-flow skill) before the first run so all subsequent cycles replay identical steps.
  • React Compiler: if react-profiler-analyze reports reactCompilerEnabled: true, do NOT propose useCallback/useMemo/React.memo unless you confirmed compiler bail-out via react-profiler-fiber-tree (absent useMemoCache).
  • Sub-agents: Phases 1–2 dispatch sub-agents — one per file for lint results, one per checklist item for semantic. Sub-agents CANNOT touch the device - all profiling and E2E verification must happen in the main agent.

Pipeline

Lint and semantic sweeps catch deterministic issues cheaply. Profiling finds runtime bottlenecks that static analysis misses. Do both.

Copy this checklist into your TODO list:

Optimization Progress:
- [ ] Phase 1: Lint sweep (deterministic — catch mechanical issues without a running app)
- [ ] Phase 2: Semantic sweep (judgment — memoization, lists, animations, etc.)
- [ ] Phase 3: Baseline profile (find real bottlenecks, fix top offenders)
- [ ] Phase 4: Verify no regressions (crashes, errors, red screens)

Phase 1: Lint sweep

Run ESLint once at the project root with a comprehensive RN performance ruleset. Dispatch sub-agents to fix results — one per file. See references/lint-rules.md for ruleset and procedure.

Phase 2: Semantic sweep

Review each area requiring judgment — memoization, list rendering, animations, async patterns, effect cleanup, state hygiene, context architecture. Dispatch one sub-agent per checklist item. See references/semantic-checklist.md for full checklist.

Phase 3: Visual profiling

  1. Load argent-react-native-profiler skill, start dual profiling
  2. Exercise key user flows (navigate screens the user specified, or all major flows)
  3. Analyze with react-profiler-analyze + native-profiler-analyze + profiler-combined-report
  4. Cross-reference profiling results with Phase 1–2 findings
  5. Fix highest-impact issues. Re-profile after architectural changes; batch mechanical fixes. If a recorded flow breaks after a fix (e.g., UI layout changed), follow argent-create-flow skill to repair the flow rather than silently discarding it.

Phase 4: Verify no regressions

Navigate every screen and UI flow within scope, confirm each renders without errors. If no scope was specified, verify the entire app — cover all reachable screens via argent-device-interact. Use debugger-log-registry to check for runtime errors and take screenshots to check for red/yellow error screens. Check for regressions introduced by fixes (e.g., fewer re-renders but higher CPU, or new jank in a different screen). Main agent only.

App-wide optimization

  1. Phase 1: run lint centrally (one command), dispatch sub-agents to fix per-file in parallel
  2. Phase 2: one sub-agent per checklist item for semantic sweep
  3. Phase 3: main agent profiles top offending screens; fixes architectural issues top-down
  4. Phase 4: main agent navigates all screens to verify nothing crashes

After the entire run, run lint again to verify no new issues were introduced with your changes. This also helps ensure you haven't missed any issues which could've been fixed.

附带文件

references/fix-reference.md
# Fix Reference

Match profiler findings and semantic sweep results to concrete fixes.

| Finding                                      | Fix                                                                           | Detail                                                                                             |
| -------------------------------------------- | ----------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------- |
| Re-renders with same props                   | `React.memo(Comp)`                                                            | **Skip if React Compiler active** — `react-profiler-analyze` reports compiler status per component |
| Expensive recomputation / unstable callbacks | `useMemo(fn, [deps])` / `useCallback(fn, [deps])`                             | `useCallback` must pair with `React.memo` on child — alone it has no effect                        |
| Inline objects/arrays in JSX                 | `StyleSheet.create()` / module-level const                                    | New reference every render breaks shallow equality                                                 |
| List jank                                    | `removeClippedSubviews`, `maxToRenderPerBatch`, `windowSize`, `getItemLayout` | Or migrate to `@shopify/flash-list` with `estimatedItemSize`                                       |
| JS-thread animation jank                     | `useNativeDriver: true` or `react-native-reanimated`                          | `useNativeDriver` only works for `transform` and `opacity` properties                              |
| Heavy work during transitions                | `InteractionManager.runAfterInteractions()`                                   | Defers execution until active animations complete                                                  |
| Slow startup                                 | Hermes + inline requires in `metro.config.js`                                 | Lazy `require()` defers loading heavy modules until first use                                      |
| Redundant, heavy, or n+1 network calls       | `view-network-logs` → `view-network-request-details`                          | Batch, debounce, or cache at the data layer                                                        |
references/lint-rules.md
# Phase 1: Lint Rules

Run once at the project root. Catches mechanical issues deterministically.
Install missing plugins before running: `npm install --save-dev eslint-plugin-react-perf`.

## Rules

### Performance (eslint-plugin-react-perf)

| Rule                                     | Catches                                                  |
| ---------------------------------------- | -------------------------------------------------------- |
| `react-perf/jsx-no-new-object-as-prop`   | Object literals `{}` as JSX props - new ref every render |
| `react-perf/jsx-no-new-array-as-prop`    | Array literals `[]` as JSX props - new ref every render  |
| `react-perf/jsx-no-new-function-as-prop` | Arrow functions / function expressions as JSX props      |
| `react-perf/jsx-no-jsx-as-prop`          | JSX elements as prop values (e.g. `icon={<Icon />}`)     |

### React (eslint-plugin-react)

| Rule                                      | Catches                                                             |
| ----------------------------------------- | ------------------------------------------------------------------- |
| `react/no-array-index-key`                | `key={index}` - incorrect reconciliation on reorder                 |
| `react/jsx-no-bind`                       | `.bind()` in JSX props - new function ref every render              |
| `react/jsx-no-constructed-context-values` | Object/array literals as Context `value` - re-renders all consumers |
| `react/no-unstable-nested-components`     | Components defined inside render - full remount each render         |
| `react/no-object-type-as-default-prop`    | Object/array defaults in destructuring (e.g. `{ items = [] }`)      |

### React Native (eslint-plugin-react-native)

| Rule                                          | Catches                                          |
| --------------------------------------------- | ------------------------------------------------ |
| `react-native/no-inline-styles`               | Inline `style={{}}` - defeats shallow comparison |
| `react-native/no-unused-styles`               | StyleSheet rules never referenced                |
| `react-native/no-color-literals`              | Color literals in styles instead of constants    |
| `react-native/no-single-element-style-arrays` | `style={[single]}` instead of `style={single}`   |

### Hooks (eslint-plugin-react-hooks)

| Rule                          | Catches                                  |
| ----------------------------- | ---------------------------------------- |
| `react-hooks/exhaustive-deps` | Missing/incorrect hook dependency arrays |
| `react-hooks/rules-of-hooks`  | Hooks called conditionally or in loops   |

### Error handling (ESLint core)

| Rule                                       | Catches                               |
| ------------------------------------------ | ------------------------------------- |
| `no-empty` (with `allowEmptyCatch: false`) | Empty catch blocks - swallowed errors |

## Procedure

1. Check if the project has an existing ESLint config.
   2a. If yes, extend it with missing rules from above.
   2b. If no config, create a temporary `.eslintrc.json` with all rules above.
2. Run: `npx eslint --format json <src_dir>` — replace `<src_dir>` with the project's JS/TS source root (check `package.json` scripts or look for `src/`, `app/`, `lib/`)
3. Parse output into: `file:line -> rule -> message`.
references/semantic-checklist.md
# Phase 2: Semantic Sweep

Work through each area. Do not skip.
See [fix-reference.md](fix-reference.md) for concrete fix patterns per finding.

## Checklist

### Memoization

Check every exported function component: is it rendered in a list, a frequently-updating parent, or a context consumer? If yes and props are stable, wrap in `React.memo`. Check context providers for unstable `value` props. Skip `React.memo` if React Compiler is active.

### List rendering

Check all list-like rendering: ScrollView+map, manually iterated arrays, deeply nested FlatLists. Verify lists use virtualization (`FlatList`/`FlashList`), stable keys, and proper item sizing.

### Animations

Check all animation code against current library best practices. Prefer Reanimated over the Animated API. Check for JS-thread animation bottlenecks (`requestAnimationFrame` loops, state-driven animations).

### Async patterns

Check for sequential `await` calls that could be `Promise.all`. Check for missing `AbortController` / cancellation on unmount. Check for fetch waterfalls (parent fetches → child fetches → grandchild fetches).

### Effect cleanup

Check all `useEffect` hooks that create timers, listeners, or subscriptions. Verify each returns a cleanup function. Check for effects missing dependency arrays (runs every render).

### State hygiene

Check for unused state (set but never rendered), unbounded state growth (arrays/objects that grow without cap), and derived state that should be computed with `useMemo` instead.

### Monolithic context

Flag but do NOT auto-fix. Report as architectural recommendation.