Skip to content

[Due for payment 2026-08-27] [$1000] Remove useOnyx's dependencies argument #94595

Closed
10 of 10 issues completed
Closed

Description

@mountiny

Coming from here

Background

useOnyx(key, options, dependencies) accepts an optional third argument: a React dependency list. useOnyx memoizes the output of options.selector, and dependencies tells it when to re-run that selector — needed because a selector usually closes over external values (a prop, other state) that the hook can't otherwise know changed. Separately, React Compiler already runs in the build pipeline and auto-memoizes values — including selectors — keyed on what they read.

Problem

When a useOnyx selector closes over an outside value such as a prop or other state, if the caller forgets to list that value in the dependencies array, then the selector keeps returning stale output and nothing catches it — dependencies is a plain positional argument, so react-hooks/exhaustive-deps never checks it. The argument also duplicates React's own dependency tracking, giving the codebase a second, parallel way to express when a selector should re-run.

Solution

Remove the dependencies argument from useOnyx. Selectors no longer need a manual dependency list at all: React Compiler memoizes each selector keyed on exactly the values it reads, so a stale selector from a forgotten dependency becomes impossible — there is no list to forget. Most selectors can be written inline in the useOnyx({selector}) call, or as a plain in-component function; the compiler stabilizes the selector reference (and the options object) the same way a hand-written useCallback would.

In E/App, migrate the ~70 call sites from useOnyx(key, options, deps) to useOnyx(key, options), dropping the deps array. Leave the selector inline (or a plain in-component function) for the files React Compiler compiles; add useCallback only where no-inline-useOnyx-selector errors (the handful of compiler bailouts).

Start with removing the dependencies in batches from the App and ultimately remove the argument from onyx.

One boundary to respect:

Compiler bailouts. A file React Compiler can't compile won't get this memoization, so its selector must be memoized by hand with useCallback. The rulesdir/no-inline-useOnyx-selector lint rule flags exactly these cases — it is suppressed for compiled files and errors for bailouts — so it tells you when useCallback is still required.

Onyx PR: Expensify/react-native-onyx#800
E/App PR: #93439

Issue OwnerCurrent Issue Owner: @hoangzinh

Activity

  1. melvin-bot commented on Jun 30, 2026

    @melvin-bot

    @fabioh8010 Huh... This is 4 days overdue. Who can take care of this?

  2. fabioh8010 commented on Jul 1, 2026

    @fabioh8010
    Contributor

    Working on this one today

  3. melvin-bot commented on Jul 6, 2026

    @melvin-bot

    @fabioh8010 Eep! 4 days overdue now. Issues have feelings too...

  4. fabioh8010 commented on Jul 8, 2026

    @fabioh8010
    Contributor

    @mountiny Could you review before I continue?

    Plan: Split useOnyx dependencies-removal into batch PRs + ESLint guard

    Verified facts this plan relies on

    • main's App wrapper src/hooks/useOnyx.ts still accepts dependencies?: DependencyList (3rd param) and forwards it; Onyx on main is 3.0.88 (still has the arg). → Call sites can drop the arg while the wrapper keeps accepting it. The wrapper/Onyx removal is the last step.
    • main contains the same 3-arg call sites this branch migrated, so each batch can be re-derived directly against main (this branch is the reference implementation, not a cherry-pick source — it sits on the divergent "onyx-store" engine).
    • ESLint: local rules live in eslint-plugin-local-rules/ (loaded via rulesdir.RULES_DIR in config/eslint/eslint.config.mjs, referenced as rulesdir/<name>, enabled in that file's rules block). Existing onyx rules (no-inline-useOnyx-selector, no-set-or-map-return-in-useOnyx-selector) live in the external eslint-config-expensify pkg (v4.0.6).
    • config/eslint/processors/eslint-processor-react-compiler-compat.mjs already suppresses rulesdir/no-inline-useOnyx-selector for files React Compiler compiles → inline selectors are lint-clean in compilable files; only React-Compiler-bailout files need useCallback.
    • eslint-seatbelt (baseline config/eslint/eslint.seatbelt.tsv) grandfathers existing violations; never hand-edited; auto-tightens on main after each merge; seed a new rule's baseline with SEATBELT_INCREASE=<rule> CI=true npm run lint.

    Decisions

    • Lint rule home: local (eslint-plugin-local-rules/) — it's a temporary guard (dies once Onyx drops the arg and TS enforces it).
    • Lint rule timing: land it first, seatbelt-grandfathering all current sites, so no new 3-arg usages land during the multi-PR rollout.
    • Granularity: ~8 feature-grouped batches, independent PRs to main.

    Change-type distribution (from full branch analysis)

    WRAPPER 1 · PURE-DROP 32 · INLINE 43 · USECALLBACK 2 · RESTRUCTURE 5 (= 83).

    • PURE-DROP – delete the , [deps] arg only; selector already stable (module fn / existing useCallback / no selector). Behavior-preserving.
    • INLINE – selector rewritten as an inline/plain arrow, relies on React Compiler memoization; arg dropped.
    • USECALLBACK – React-Compiler-bailout files (BaseKYCWall, CreateReportMenuItem); selector wrapped in useCallback.
    • RESTRUCTURE – real logic changes, review individually: MoneyRequestView, MoneyRequestConfirmationList/sections/InvoiceSenderField, hooks/useParticipantsPolicies, hooks/useParticipantsPolicyTags, Travel/TripDetailsPage.

    Phase 1 — PR #1: ESLint guard (land first)

    Goal: forbid new 3rd-arg useOnyx usages; grandfather existing ones so batches can proceed incrementally.

    New file eslint-plugin-local-rules/no-useonyx-dependencies-arg.js (match the export {name, meta, create} convention of require-a11y-disable-justification.js):

    const name = 'no-useonyx-dependencies-arg';
    
    const meta = {
        type: 'problem',
        docs: {
            description: 'Disallow the deprecated 3rd `dependencies` argument of useOnyx(). ' + 'React Compiler memoizes selectors; keep the selector reference stable instead.',
            recommended: 'error',
        },
        schema: [],
        messages: {
            noDependenciesArg:
                'The 3rd `dependencies` argument of useOnyx() is deprecated and being removed (#94595).\n\n' +
                'Do not pass a dependency array. Keep the selector reference stable instead:\n' +
                '- Prefer an inline or module-level selector (React Compiler memoizes it automatically).\n' +
                '- In React-Compiler-bailout files, wrap the selector in useCallback with the relevant deps.',
        },
    };
    
    function create(context) {
        return {
            CallExpression(node) {
                if (node.callee.type !== 'Identifier' || node.callee.name !== 'useOnyx') {
                    return;
                }
                if (node.arguments.length < 3) {
                    return;
                }
                context.report({node: node.arguments[2], messageId: 'noDependenciesArg'});
            },
        };
    }
    
    export {name, meta, create};
    • No autofix — blindly deleting the arg without stabilizing the selector can cause selector-identity churn (re-runs / perf regressions). Authors must fix deliberately.
    • Matches any useOnyx identifier (both @hooks/useOnyx and the restricted react-native-onyx import). CallExpression visitor also catches non-destructured calls (more robust than the sibling rules' VariableDeclarator approach).

    Wire it up in config/eslint/eslint.config.mjs rules block (next to the other rulesdir/* entries, ~line 330):

    'rulesdir/no-useonyx-dependencies-arg': 'error',

    Seed the seatbelt baseline (grandfather current sites): SEATBELT_INCREASE=rulesdir/no-useonyx-dependencies-arg CI=true npm run lint, then commit the regenerated config/eslint/eslint.seatbelt.tsv. From that point new/increased 3-arg usage fails CI; each batch shrinks the baseline (auto-tightened on main).

    Verify: npm run lint passes; add a throwaway useOnyx(k, {}, []) in a scratch file → confirm it errors; remove it.


    Phase 2 — Migration batches (independent PRs to main)

    Each batch: branch off main, apply the transform to its files (this branch = reference; re-derive RESTRUCTURE files against main's current code, don't blind-copy), then run the full per-PR verification (below). All 82 non-wrapper files are covered; src/hooks/useOnyx.ts is intentionally excluded (Phase 3).

    Batch Theme Files Notes / risk
    A Low-risk shared data hooks hooks/: useActiveAdminPolicies, useDefaultFundID, useExpensifyCardFeeds, useHasPerDiemTransactions, useOnboardingTaskInformation, usePaginatedReportActions, useParentReportAction, usePaymentOptions, usePolicyData/index, usePolicyForTransaction, useSplitEffectivePolicy, useDistanceRateOriginalPolicy, useTransactionThread (13) All PURE-DROP. Warm-up batch; unit tests + typecheck carry most weight.
    B Transaction/report/policy shared hooks hooks/: useReportTransactions, useTransactionsByID, useTransactionViolation, useTransactionViolationOfWorkspace, useTripTransactions, useResetBankAccountModal, useReportPrimaryAction, useSelectionModeReportActions, useShouldShowEmptyReportConfirmation, useShowNotFoundPageInIOUStep, useParticipantsPolicies, useParticipantsPolicyTags (12) INLINE + 2 RESTRUCTURE (participants* factory signature participants→policyIDs). Review the 2 RESTRUCTURE closely.
    C Search Search/FilterComponents/CategorySelector; Search/SearchList/ListItem/{ExpenseReportListItem,GroupHeader,ReportListItemHeader,TaskListItem,TransactionGroupListItem,TransactionListItem/index}; Search/SearchPageHeader/SearchActionsBarCreateButton; pages/Search/SearchHoldReasonPage (9) INLINE-heavy; list-row rendering.
    D Money Request — headers, preview & primary actions MoneyReportHeaderActions/{MoneyReportHeaderSecondaryActions,MoneyReportHeaderSelectionDropdown}; MoneyReportHeaderPrimaryAction/SubmitPrimaryAction; ReportActionItem/MoneyRequestReportPreview/{MoneyRequestReportPreviewProvider,ReportPreviewActionButton,SubmitActionButton}; hooks/useLifecycleActions; pages/ReportSubmitToContent; TransactionItemRow/DataCells/ChatBubbleCell (9) Pay/approve/submit dropdowns + report preview.
    E Money Request — views, confirmation & expense flows ReportActionItem/{MoneyRequestView,MoneyRequestReceiptView}; MoneyRequestConfirmationList/sections/{ReportField,InvoiceSenderField}; pages/AddExistingExpense; pages/iou/SplitExpenseEditPage; pages/RejectExpenseReportPage; KYCWall/BaseKYCWall (8) Contains RESTRUCTURE (MoneyRequestView, InvoiceSenderField) + USECALLBACK (BaseKYCWall). Highest-touch UI batch.
    F Report / Inbox chat ChronosTimerHeaderButton; pages/inbox/report/useActiveDraftReportAction; ReportActionCompose/SuggestionMention; actionContents/{ChatActionableButtons,ReimbursementQueuedContent}; ReactionList/PopoverReactionList; Reactions/ReactionTooltipContent; ReportActionItem; ReportActionItemCreated; ReportActionItemParentAction; settings/Report/ReportDetailsColumnsPage; tasks/NewTaskDetailsPage (12) Chat rendering + reactions + mentions.
    G Workspace / Policy / Domain / Dynamic report Tables/WorkspaceListTable/{LeaveWorkspaceFlow,WorkspaceRowThreeDotsMenu,WorkspaceRowBrickRoadIndicator}; pages/workspace/{WorkspaceOverviewPage,WorkspacesListPage}; workspace/rooms/WorkspaceRoomsPage; domain/Members/{DomainAddMemberPage,DomainReportSuspiciousActivityPage,MoveUserBetweenGroupsPage}; pages/{DynamicReportDetailsPage,DynamicReportChangeWorkspacePage} (11) Workspace list/error indicators + domain admin.
    H Navigation, Wallet, Travel, Debug Navigation/NavigationTabBar/InboxTabButton; Navigation/QuickCreationActionsBar/index; inbox/sidebar/FABPopoverContent/menuItems/CreateReportMenuItem; settings/Wallet/ExpensifyCardPage/index; Travel/TripDetailsPage; Debug/Report/{DebugReportActions,DebugReportPage}; Debug/ReportAction/DebugReportActionPage (8) RESTRUCTURE (TripDetailsPage) + USECALLBACK (CreateReportMenuItem). Mixed leftovers.

    Batches are independent (disjoint files, localized edits) → mergeable in any order/parallel; conflicts unlikely.

    Per-PR verification (every batch)

    1. npm run fmt on changed files.
    2. npm run lint-changed — seatbelt count for the rule must drop for touched files (never increase).
    3. npm run typecheck — must stay green (wrapper still 3-arg, so 2-arg calls type-check fine).
    4. npm run react-compiler-compliance-check check <files> — every changed component/hook must compile; USECALLBACK files are expected to stay bailed-out (BaseKYCWall, CreateReportMenuItem already fail on main — confirm no new failure vs main).
    5. Relevant unit tests (npm run test for touched areas).
    6. Manual smoke test of the batch's flows (see per-batch steps in the PR templates) — focus on selector-identity regressions: correct data renders, no infinite re-render, no new JS console errors.

    Phase 3 — Final PR: remove the argument (coordinated with Onyx)

    Prereq: Onyx #800 merged/published (removes dependencies, adds createMemoizedSelector, deletes useLiveRef) and all batches A–H merged (seatbelt baseline for the rule = 0).

    App final PR:

    • Bump react-native-onyx to the deps-removed version (package.json + lockfile).
    • src/hooks/useOnyx.ts: drop the dependencies param + stop forwarding it to originalUseOnyx (this is the branch's WRAPPER change).
    • Delete eslint-plugin-local-rules/no-useonyx-dependencies-arg.js + its config entry + its (now-empty) seatbelt rows — redundant once TS enforces the 2-arg signature.
    • Grep for any useOnyx(..., ..., ...) that landed after the batches and migrate; add any new hooks that used the arg. Check App doesn't reference useLiveRef; adopt createMemoizedSelector only where genuinely needed.
    • Verify: full npm run typecheck (now the compiler enforces no 3rd arg), npm run lint, npm run test.

    Batch-specific Tests/QA steps

    • A (low-risk hooks): Open a workspace/expense report and a chat; confirm policies, payment options, per-diem, paginated report actions, transactions all load. Emphasize npm run test + typecheck (pure no-ops).
    • B (txn/report/policy hooks): Open an expense report with transactions & violations; open a Trip room (trip transactions); reject/submit flows; participant-policy pickers (RESTRUCTURE) — verify correct policies/tags resolve.
    • C (Search): Open Search; switch types (Expenses/Reports/Chats/Tasks); verify row content (submitter names, avatars, violation dots, group headers); category filter; bulk-select + hold-reason page.
    • D (MR headers/preview): Open an IOU/expense report; verify Pay/Approve/Submit dropdowns and KYC gating; report preview card in chat; submit primary action; chat-bubble cell in transaction rows.
    • E (MR views/confirmation): Open MoneyRequestView (edit fields), receipt view, split-expense edit, reject-expense page, invoice sender field, report field selector; verify amounts/participants/policies. Note BaseKYCWall stays compiler-bailout.
    • F (Report/Inbox chat): Open chats; verify "created" system message, parent-action thread, reactions + reaction tooltip, reimbursement-queued content, @mentions in composer, task details, report details columns.
    • G (Workspace/Domain): Workspaces list + overview (owned-policy counts), rooms page, leave-workspace flow, brick-road error indicators, domain member add/suspicious-activity/move pages, dynamic report change-workspace.
    • H (misc): Bottom-tab Inbox button (unread state), FAB create-report menu, Expensify Card page, Trip details (RESTRUCTURE — verify traveler details), Debug report/report-action pages.

    Execution checklist

    1. Open PR 1 (lint rule + seatbelt seed) → merge.
    2. Open batches A→H as independent PRs off main (parallelizable), each passing the per-PR verification; watch the seatbelt count for the rule tick down.
    3. After Onyx PR lands and all batches merge, open the Final PR (Onyx bump + wrapper param removal + rule deletion).
  5. mountiny commented on Jul 8, 2026

    @mountiny
    ContributorAuthor

    @fabioh8010 Looks good! I can create the sub issues for this

  6. 83 remaining items

  7. changed the title [-]Remove useOnyx's dependencies argument[/-] [+][Due for payment 2026-08-27] Remove useOnyx's dependencies argument[/+] on Aug 20, 2026
  8. melvin-bot commented on Aug 20, 2026

    @melvin-bot

    @hoangzinh

    The solution for this issue has been 🚀 deployed to production 🚀 in version 9.4.56-3 and is now subject to a 7-day regression period 📆. Here is the list of pull requests that resolve this issue:

    If no regressions arise, payment will be issued on 2026-08-27. 🎊

    The following checklist (instructions) will need to be completed before the issue can be closed. Please copy/paste the BugZero Checklist from here into a new comment on this GH and complete it. If you have the K2 extension, you can simply click: [this button]. If no checklist is needed for this issue, you can click: [no checklist button]

  9. changed the title [-][Due for payment 2026-08-27] Remove useOnyx's dependencies argument[/-] [+][Due for payment 2026-08-27] [$1000] Remove useOnyx's dependencies argument[/+] on Aug 20, 2026
  10. melvin-bot commented on Aug 20, 2026

    @melvin-bot

    ⚠️ Could not update price automatically because there is no linked Upwork Job ID. The BZ team member will need to update the price manually in Upwork.

  11. melvin-bot commented on Aug 25, 2026

    @melvin-bot

    @hoangzinh Huh... This is 4 days overdue. Who can take care of this?

  12. hoangzinh commented on Aug 26, 2026

    @hoangzinh
    Contributor

    All done here. Just waiting for the regression period and doing payment. We don't need a C+ checklist for this issue.

  13. added
    Awaiting PaymentAuto-added when associated PR is deployed to production
    and removed on Aug 26, 2026
  14. melvin-bot commented on Aug 26, 2026

    @melvin-bot

    Triggered auto assignment to @mallenexpensify (Awaiting Payment)

  15. mallenexpensify commented on Aug 27, 2026

    @mallenexpensify
    Contributor

    Payment Summary

    Contributor+: @hoangzinh due $1000 via NewDot

  16. laurenreidexpensify commented on Aug 31, 2026

    @laurenreidexpensify
    Contributor

    $1000 approved @hoangzinh New Expensify

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Labels

Awaiting PaymentAuto-added when associated PR is deployed to productionDailyKSv2Task

Type

No type

Projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions