|
| 1 | +--- |
| 2 | +ruleId: PERF-19 |
| 3 | +title: Collection selectors return only what the consumer uses |
| 4 | +--- |
| 5 | + |
| 6 | +## [PERF-19] Collection selectors return only what the consumer uses |
| 7 | + |
| 8 | +### Reasoning |
| 9 | + |
| 10 | +`useOnyx` runs `deepEqual` on a selector's output whenever the input reference changes. For a collection key such as `policy_`, `report_` or `transaction_`, that reference changes on **every write to any member of the collection**, so the compare runs constantly and its cost scales with the size of whatever the selector returns. |
| 11 | + |
| 12 | +A selector that returns an array or map of records when the consumer only reads an ID and a `length > 1` check pays that compare for nothing. On a large account the collection can hold thousands of records, so a single compare costs tens of milliseconds and a render cycle that triggers several of them costs hundreds. Returning the scalars removes the compare entirely. |
| 13 | + |
| 14 | +When the component also needs one full record, subscribe to that single member key separately. A single-key subscription without a selector compares by reference, so the extra subscription costs nothing. |
| 15 | + |
| 16 | +This is a narrower case than [PERF-11](perf-11-optimize-data-selection.md), which covers selector sizing in general. PERF-19 applies only when the fix is provable from the code you can see: nothing the component keeps from the selector output is an object, and every function needed to produce the scalars is already reachable from the selector. If either is untrue, this rule does not apply. |
| 17 | + |
| 18 | +### Incorrect |
| 19 | + |
| 20 | +```tsx |
| 21 | +// BAD: the selector returns every matching report, so useOnyx deep-compares all of them |
| 22 | +// on each report_ update. The component only asks whether there are any. |
| 23 | +const [reportsWithErrors] = useOnyx(ONYXKEYS.COLLECTION.REPORT, { |
| 24 | + selector: (reports) => Object.values(reports ?? {}).filter((report) => !!report?.errors), |
| 25 | +}); |
| 26 | +const hasErrors = reportsWithErrors.length > 0; |
| 27 | +``` |
| 28 | + |
| 29 | +```tsx |
| 30 | +// BAD: the array is passed whole into a util, but the component only keeps an ID off the result, |
| 31 | +// and the other usage is a length check. Nothing derived from the array escapes as an object, |
| 32 | +// so the whole chain can move into the selector. |
| 33 | +const [activeReports] = useOnyx(ONYXKEYS.COLLECTION.REPORT, { |
| 34 | + selector: (reports) => getActiveReports(reports), |
| 35 | +}); |
| 36 | +const defaultReportID = pickDefaultReport(activeReports, activeWorkspaceID)?.reportID; |
| 37 | +const hasMultipleActiveReports = activeReports.length > 1; |
| 38 | +``` |
| 39 | + |
| 40 | +### Correct |
| 41 | + |
| 42 | +```tsx |
| 43 | +// GOOD: the selector returns the boolean, so there is nothing expensive left to compare. |
| 44 | +const [hasErrors] = useOnyx(ONYXKEYS.COLLECTION.REPORT, { |
| 45 | + selector: (reports) => Object.values(reports ?? {}).some((report) => !!report?.errors), |
| 46 | +}); |
| 47 | +``` |
| 48 | + |
| 49 | +```tsx |
| 50 | +// GOOD: the whole chain moved into the selector, which now returns two scalars. |
| 51 | +const [reportSelection] = useOnyx(ONYXKEYS.COLLECTION.REPORT, { |
| 52 | + selector: (reports) => { |
| 53 | + const activeReports = getActiveReports(reports); |
| 54 | + return { |
| 55 | + defaultReportID: pickDefaultReport(activeReports, activeWorkspaceID)?.reportID, |
| 56 | + hasMultipleActiveReports: activeReports.length > 1, |
| 57 | + }; |
| 58 | + }, |
| 59 | +}); |
| 60 | + |
| 61 | +// The one record the component renders comes from a single-member subscription, which compares by reference. |
| 62 | +const [defaultReport] = useOnyx(`${ONYXKEYS.COLLECTION.REPORT}${getNonEmptyStringOnyxID(reportSelection?.defaultReportID)}`); |
| 63 | +``` |
| 64 | + |
| 65 | +### Not a violation |
| 66 | + |
| 67 | +```tsx |
| 68 | +// The report objects are rendered, so they have to escape the selector. Nothing to reduce. |
| 69 | +const [activeReports] = useOnyx(ONYXKEYS.COLLECTION.REPORT, {selector: getActiveReports}); |
| 70 | + |
| 71 | +return <SelectionList sections={[{data: activeReports.map(toListItem)}]} />; |
| 72 | +``` |
| 73 | + |
| 74 | +```tsx |
| 75 | +// Single-item key, not a collection. Picking a few fields here is already the right shape. |
| 76 | +const [user] = useOnyx(`${ONYXKEYS.USER}${userId}`, { |
| 77 | + selector: (user) => ({name: user?.name, avatar: user?.avatar}), |
| 78 | +}); |
| 79 | +``` |
| 80 | + |
| 81 | +--- |
| 82 | + |
| 83 | +### Review Metadata |
| 84 | + |
| 85 | +**Flag when ALL of these are true:** |
| 86 | + |
| 87 | +- The `useOnyx` call subscribes to a collection key (`ONYXKEYS.COLLECTION.*`, or a derived key whose value is a collection) **and** passes a `selector`. The selector may be inline or imported from `src/selectors/*`. If it is imported, read its definition before judging its return shape. |
| 88 | +- The selector returns an object graph: an array of Onyx records, a keyed object of records, or an object with nested records. A scalar or a flat record of primitives is already correct. |
| 89 | +- **Nothing derived from the selector output escapes as an object or array.** For every usage site of the output, follow it through intermediate calls to what the component finally keeps, and flag only if all of them end in a scalar. Include aliases and re-destructuring. |
| 90 | + - Escapes: the branch ends in JSX, a prop, `useState`, a context value, a ref, or the return value of an exported hook in the file. |
| 91 | + - Does not escape: the output is passed whole into a util and the component only reads a scalar off that util's result, because the whole chain can move into the selector. |
| 92 | +- **Every function needed to compute the scalars is already reachable from the selector**: defined in the file, imported into it, or exported from a module the file already imports. Moving the chain into the selector must not require new branching, a new data source, or an Onyx value the selector does not already receive. A named wrapper that only calls those reachable functions and returns their scalar results counts as reachable; logic those functions do not already provide does not. |
| 93 | + |
| 94 | +Increase confidence (not required): |
| 95 | + |
| 96 | +- The collection is a hot one (`policy_`, `report_`, `transaction_`, `transaction_draft_`), so the compare runs on a high-frequency write path. |
| 97 | +- The selector output feeds a `useMemo`/`useCallback` dependency array only through a scalar (`x.length`, `x?.id`), which makes the reduction mechanical. |
| 98 | + |
| 99 | +**DO NOT flag if:** |
| 100 | + |
| 101 | +- Any branch of the data flow ends with the objects themselves: rendered in a list, passed as a prop, stored in state, or returned from an exported hook. |
| 102 | +- The chain cannot be traced. If the output goes into a callee whose body is not in the diff, search the callee; if what it yields still cannot be confirmed, do not flag. |
| 103 | +- The key is a single-item key rather than a collection. Picking a few fields from one record is already the correct pattern. |
| 104 | +- Computing the scalars needs logic that does not exist yet, a value the selector has no access to, or a new Onyx subscription to feed the selector itself. |
| 105 | +- The selector already returns scalars and the object graph comes from a separate single-member subscription. |
| 106 | + |
| 107 | +**Overlap with PERF-11:** PERF-19 is the narrower case. When both match the same line, report PERF-19 only. |
| 108 | + |
| 109 | +**Search Patterns** (hints for reviewers): |
| 110 | +- `useOnyx\(ONYXKEYS\.COLLECTION` |
| 111 | +- `selector: \(` |
| 112 | +- `selector: [a-z][A-Za-z]*Selector` |
| 113 | +- `Object\.(values|entries|keys)\(.*\)\.(filter|map)` |
| 114 | +- `OnyxCollection<` |
0 commit comments