Skip to content

Remove onyx connect for the key: ONYXKEYS.PERSONAL_DETAILS_LIST in Parser lib - Part 1 - #92758

Merged
youssef-lr merged 15 commits into
Expensify:mainfrom
hoangzinh:fix/issue-66387-remove-onyx-connect-personal-details-parser
Aug 29, 2026
Merged

youssef-lr merged 15 commits into
Expensify:mainfrom
hoangzinh:fix/issue-66387-remove-onyx-connect-personal-details-parser

Conversation

@hoangzinh

@hoangzinh hoangzinh commented Jun 5, 2026

Copy link
Copy Markdown
Contributor

Explanation of Change

This is Part 1 of a series focused on removing Onyx Connect for the key ONYXKEYS.PERSONAL_DETAILS_LIST in the Parser library. In this pull request, we will:

  • Introduce a new hook useAccountIDToNameMap
  • Apply this key in Task pages

Why a plain useOnyx + useMemo hook (not a selector or a context provider)? I benchmarked all three (Reassure, on a 20k-PD account) before deciding:

  • Selector — rejected. A useOnyx(PERSONAL_DETAILS_LIST, {selector}) returning this same-size map makes Onyx run deepEqual over the whole map on every PERSONAL_DETAILS_LIST write, related or not. That's ~2.24 ms/write at 20k PDs — versus the ~0.02 ms Parser.htmlToMarkdown re-run it would save by skipping a re-render. It also violates PERF-11 ("selector maps an entire collection → expensive deepEqual").

  • Context provider — rejected. It gives no re-render benefit: its useMemo recomputes a new map reference on every PD write, so consumers re-render exactly as often as the plain hook (11 vs 11 in the benchmark). It only adds indirection plus an always-mounted global computation that runs even when no Task page is open.

  • Raw inline hook — chosen. No large-map deepEqual (cheap shallowEqual), PERF-11-compliant, and only computes while a Task page is mounted. The extra re-renders it "costs" are trivial (the Parser reparse is ~0.02 ms), far cheaper than the selector's per-write comparison.

Approach re-renders on unrelated PD churn per-write cost @20k PERF-11
selector few ~2.24 ms deepEqual
context provider many (same as raw) map rebuild + provider layer
raw useMemo hook many (cheap) map rebuild + ~0.02 ms reparse

See: #92758 (comment)

Fixed Issues

$ #66387
PROPOSAL:

Tests

  • Verify that no errors appear in the JS console

Offline tests

QA Steps

// TODO: These must be filled out, or the issue title must include "[No QA]."

  1. Go to any report.
  2. Create a task with a description that mentions a user to perform a specific action. For example, @<user_login> please complete the report by Friday.
  3. Open that task report
  4. Open the task description modal.
  5. Verify that the task description displays as @<user_login> please complete the report by Friday.
  • Verify that no errors appear in the JS console

PR Author Checklist

  • I linked the correct issue in the ### Fixed Issues section above
  • I wrote clear testing steps that cover the changes made in this PR
    • I added steps for local testing in the Tests section
    • I added steps for the expected offline behavior in the Offline steps section
    • I added steps for Staging and/or Production testing in the QA steps section
    • I added steps to cover failure scenarios (i.e. verify an input displays the correct error message if the entered data is not correct)
    • I turned off my network connection and tested it while offline to ensure it matches the expected behavior (i.e. verify the default avatar icon is displayed if app is offline)
    • I tested this PR with a High Traffic account against the staging or production API to ensure there are no regressions (e.g. long loading states that impact usability).
  • I included screenshots or videos for tests on all platforms
  • I ran the tests on all platforms & verified they passed on:
    • Android: Native
    • Android: mWeb Chrome
    • iOS: Native
    • iOS: mWeb Safari
    • MacOS: Chrome / Safari
  • I verified there are no console errors (if there's a console error not related to the PR, report it or open an issue for it to be fixed)
  • I followed proper code patterns (see Reviewing the code)
    • I verified that any callback methods that were added or modified are named for what the method does and never what callback they handle (i.e. toggleReport and not onIconClick)
    • I verified that comments were added to code that is not self explanatory
    • I verified that any new or modified comments were clear, correct English, and explained "why" the code was doing something instead of only explaining "what" the code was doing.
    • I verified any copy / text shown in the product is localized by adding it to src/languages/* files and using the translation method
    • I verified all numbers, amounts, dates and phone numbers shown in the product are using the localization methods
    • I verified any copy / text that was added to the app is grammatically correct in English. It adheres to proper capitalization guidelines (note: only the first word of header/labels should be capitalized), and is either coming verbatim from figma or has been approved by marketing (in order to get marketing approval, ask the Bug Zero team member to add the Waiting for copy label to the issue)
    • I verified proper file naming conventions were followed for any new files or renamed files. All non-platform specific files are named after what they export and are not named "index.js". All platform-specific files are named for the platform the code supports as outlined in the README.
    • I verified the JSDocs style guidelines (in STYLE.md) were followed
  • If a new code pattern is added I verified it was agreed to be used by multiple Expensify engineers
  • I followed the guidelines as stated in the Review Guidelines
  • I tested other components that can be impacted by my changes (i.e. if the PR modifies a shared library or component like Avatar, I verified the components using Avatar are working as expected)
  • I verified all code is DRY (the PR doesn't include any logic written more than once, with the exception of tests)
  • I verified any variables that can be defined as constants (ie. in CONST.ts or at the top of the file that uses the constant) are defined as such
  • I verified that if a function's arguments changed that all usages have also been updated correctly
  • If any new file was added I verified that:
    • The file has a description of what it does and/or why is needed at the top of the file if the code is not self explanatory
  • If a new CSS style is added I verified that:
    • A similar style doesn't already exist
    • The style can't be created with an existing StyleUtils function (i.e. StyleUtils.getBackgroundAndBorderStyle(theme.componentBG))
  • If new assets were added or existing ones were modified, I verified that:
    • The assets are optimized and compressed (for SVG files, run npm run compress-svg)
    • The assets load correctly across all supported platforms.
  • If the PR modifies code that runs when editing or sending messages, I tested and verified there is no unexpected behavior for all supported markdown - URLs, single line code, code blocks, quotes, headings, bold, strikethrough, and italic.
  • If the PR modifies a generic component, I tested and verified that those changes do not break usages of that component in the rest of the App (i.e. if a shared library or component like Avatar is modified, I verified that Avatar is working as expected in all cases)
  • If the PR modifies a component related to any of the existing Storybook stories, I tested and verified all stories for that component are still working as expected.
  • If the PR modifies a component or page that can be accessed by a direct deeplink, I verified that the code functions as expected when the deeplink is used - from a logged in and logged out account.
  • If the PR modifies the UI (e.g. new buttons, new UI components, changing the padding/spacing/sizing, moving components, etc) or modifies the form input styles:
    • I verified that all the inputs inside a form are aligned with each other.
    • I added Design label and/or tagged @Expensify/design so the design team can review the changes.
  • If a new page is added, I verified it's using the ScrollView component to make it scrollable when more elements are added to the page.
  • I added unit tests for any new feature or bug fix in this PR to help automatically prevent regressions in this user flow.
  • If the main branch was merged into this PR after a review, I tested again and verified the outcome was still expected according to the Test steps.

Screenshots/Videos

Screen.Recording.2026-06-05.at.17.31.15.mov

hoangzinh and others added 3 commits June 5, 2026 15:57
Adds a new OnyxDerived value that builds a Record<accountID, name>
from PERSONAL_DETAILS_LIST, replacing ad-hoc Onyx.connect calls that
were scattered across modules.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
Task title/description pages now pass the accountIDToNameMap derived
value to htmlToMarkdown so user @mentions render as names instead of
raw HTML in task fields.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
…tIDToName

Covers mention resolution via accountIDToName map and the @hidden
fallback when the accountID is absent.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
@codecov

codecov Bot commented Jun 5, 2026

Copy link
Copy Markdown

Codecov Report

✅ Changes either increased or maintained existing code coverage, great job!

Files with missing lines Coverage Δ
src/hooks/useAccountIDToNameMap.ts 88.88% <88.88%> (ø)
src/pages/tasks/DynamicNewTaskDescriptionPage.tsx 0.00% <0.00%> (ø)
src/pages/tasks/DynamicNewTaskTitlePage.tsx 0.00% <0.00%> (ø)
src/pages/tasks/TaskDescriptionPage.tsx 0.00% <0.00%> (ø)
src/pages/tasks/TaskTitlePage.tsx 0.00% <0.00%> (ø)
src/pages/tasks/DynamicNewTaskDetailsPage.tsx 0.00% <0.00%> (ø)
... and 80 files with indirect coverage changes

hoangzinh added 3 commits June 5, 2026 17:04
Switch to import type, and use a buildList helper to avoid numeric
object literal keys that violate the naming-convention rule.
@hoangzinh
hoangzinh marked this pull request as ready for review June 5, 2026 11:01
@hoangzinh
hoangzinh requested review from a team as code owners June 5, 2026 11:01
@melvin-bot
melvin-bot Bot requested review from DylanDylann and flaviadefaria and removed request for a team June 5, 2026 11:01
@melvin-bot

melvin-bot Bot commented Jun 5, 2026

Copy link
Copy Markdown

@DylanDylann Please copy/paste the Reviewer Checklist from here into a new comment on this PR and complete it. If you have the K2 extension, you can simply click: [this button]

@flaviadefaria

Copy link
Copy Markdown
Contributor

No new product considerations - removing my assignment and unsubscribing.

@DylanDylann

Copy link
Copy Markdown
Contributor

@shubham1206agra Hi, could you take over this?

@shubham1206agra

Copy link
Copy Markdown
Contributor

@hoangzinh Please fix conflicts here

key: ONYXKEYS.DERIVED.ACCOUNT_ID_TO_NAME_MAP,
dependencies: [ONYXKEYS.PERSONAL_DETAILS_LIST],
compute: ([personalDetailsList]) => {
const accountIDToNameMap: Record<string, string> = {};

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This will not create a stable reference. Will cause performance issues. cc @TMisiukiewicz for confirmation.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

sorry @shubham1206agra. Can you share your suggestion here?

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@MelvinBot Do you have any suggestion for this?

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The concern is valid. compute rebuilds the entire map into a brand-new object on every change to PERSONAL_DETAILS_LIST. That key is high-traffic (presence, avatars, timezone, lastVisited, etc. all live on personal details), so any unrelated update produces a new top-level reference for ACCOUNT_ID_TO_NAME_MAP. Every consumer that does useOnyx(ONYXKEYS.DERIVED.ACCOUNT_ID_TO_NAME_MAP) — the Task pages here — then re-renders and re-runs Parser.htmlToMarkdown even when no name actually changed.

Suggested fix: use the compute context to do an incremental update instead of a full rebuild. compute already receives {currentValue, sourceValues} (types.ts:32), so you can update only the accountIDs that appear in sourceValues and return currentValue untouched when nothing name-relevant changed — keeping the reference stable across unrelated personal-details churn.

reportAttributes.ts is the reference pattern in the codebase: it uses hasKeyTriggeredCompute(ONYXKEYS.PERSONAL_DETAILS_LIST, sourceValues) and bails out early returning currentValue when there's no relevant change (reportAttributes.ts:233, :240).

Sketch
compute: ([personalDetailsList], {currentValue, sourceValues}) => {
    const changed = sourceValues?.[ONYXKEYS.PERSONAL_DETAILS_LIST];
    // First run / full rebuild when we have no prior value or no delta to work from.
    if (!currentValue || !changed) {
        const map: Record<string, string> = {};
        for (const details of Object.values(personalDetailsList ?? {})) {
            if (!details) {
                continue;
            }
            map[details.accountID] = details.login ?? details.displayName ?? '';
        }
        return map;
    }

    // Incremental: only touch the accountIDs that actually changed.
    const next = {...currentValue};
    let dirty = false;
    for (const details of Object.values(changed)) {
        if (!details) {
            continue;
        }
        const name = details.login ?? details.displayName ?? '';
        if (next[details.accountID] !== name) {
            next[details.accountID] = name;
            dirty = true;
        }
    }
    return dirty ? next : currentValue; // stable reference when nothing relevant changed
},

One more thing worth noting: the sibling loginToAccountIDMap.ts (already merged) has the exact same full-rebuild pattern, so if you standardize on the incremental approach it's worth applying there too in a follow-up.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@MelvinBot I was looking for ref stability, not compute perf per se.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Introduce a new derived Onyx key

I know this is not stated anywhere (yet), but the overall tendency is to not introduce any new derived values as they can cause more harm than benefit and will have to be migrated away from either way.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yeah I'm not sure about moving forward with this PR if we are planning to deprecate derived values

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

have to be migrated away from either way

@adhorodyski, do we have the alternative for derived values, or is it still being discussed?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@adhorodyski should we temporarily accept this approach until we find an alternative solution for this?

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@hoangzinh Use provider for this approach. It was discussed here https://expensify.slack.com/archives/C05LX9D6E07/p1784815483529589

@shubham1206agra

Copy link
Copy Markdown
Contributor

Reviewer Checklist

  • I have verified the author checklist is complete (all boxes are checked off).
  • I verified the correct issue is linked in the ### Fixed Issues section above
  • I verified testing steps are clear and they cover the changes made in this PR
    • I verified the steps for local testing are in the Tests section
    • I verified the steps for Staging and/or Production testing are in the QA steps section
    • I verified the steps cover any possible failure scenarios (i.e. verify an input displays the correct error message if the entered data is not correct)
    • I turned off my network connection and tested it while offline to ensure it matches the expected behavior (i.e. verify the default avatar icon is displayed if app is offline)
  • I checked that screenshots or videos are included for tests on all platforms
  • I included screenshots or videos for tests on all platforms
  • I verified that the composer does not automatically focus or open the keyboard on mobile unless explicitly intended. This includes checking that returning the app from the background does not unexpectedly open the keyboard.
  • I verified tests pass on all platforms & I tested again on:
    • Android: HybridApp
    • Android: mWeb Chrome
    • iOS: HybridApp
    • iOS: mWeb Safari
    • MacOS: Chrome / Safari
  • If there are any errors in the console that are unrelated to this PR, I either fixed them (preferred) or linked to where I reported them in Slack
  • I verified proper code patterns were followed (see Reviewing the code)
    • I verified that any callback methods that were added or modified are named for what the method does and never what callback they handle (i.e. toggleReport and not onIconClick).
    • I verified that comments were added to code that is not self explanatory
    • I verified that any new or modified comments were clear, correct English, and explained "why" the code was doing something instead of only explaining "what" the code was doing.
    • I verified any copy / text that was added to the app is grammatically correct in English. It adheres to proper capitalization guidelines (note: only the first word of header/labels should be capitalized), and is either coming verbatim from figma or has been approved by marketing (in order to get marketing approval, ask the Bug Zero team member to add the Waiting for copy label to the issue)
  • If a new code pattern is added I verified it was agreed to be used by multiple Expensify engineers
  • I verified that this PR follows the guidelines as stated in the Review Guidelines
  • I verified other components that can be impacted by these changes have been tested, and I retested again (i.e. if the PR modifies a shared library or component like Avatar, I verified the components using Avatar have been tested & I retested again)
  • If a new component is created I verified that:
    • A similar component doesn't exist in the codebase
    • All props are defined accurately and each prop has a /** comment above it */
    • The file is named correctly
    • The component has a clear name that is non-ambiguous and the purpose of the component can be inferred from the name alone
    • The only data being stored in the state is data necessary for rendering and nothing else
    • For Class Components, any internal methods passed to components event handlers are bound to this properly so there are no scoping issues (i.e. for onClick={this.submit} the method this.submit should be bound to this in the constructor)
    • Any internal methods bound to this are necessary to be bound (i.e. avoid this.submit = this.submit.bind(this); if this.submit is never passed to a component event handler like onClick)
    • All JSX used for rendering exists in the render method
    • The component has the minimum amount of code necessary for its purpose, and it is broken down into smaller components in order to separate concerns and functions
  • If any new file was added I verified that:
    • The file has a description of what it does and/or why is needed at the top of the file if the code is not self explanatory
  • If a new CSS style is added I verified that:
    • A similar style doesn't already exist
    • The style can't be created with an existing StyleUtils function (i.e. StyleUtils.getBackgroundAndBorderStyle(theme.componentBG)
  • If the PR modifies code that runs when editing or sending messages, I tested and verified there is no unexpected behavior for all supported markdown - URLs, single line code, code blocks, quotes, headings, bold, strikethrough, and italic.
  • If the PR modifies a generic component, I tested and verified that those changes do not break usages of that component in the rest of the App (i.e. if a shared library or component like Avatar is modified, I verified that Avatar is working as expected in all cases)
  • If the PR modifies a component related to any of the existing Storybook stories, I tested and verified all stories for that component are still working as expected.
  • If the PR modifies a component or page that can be accessed by a direct deeplink, I verified that the code functions as expected when the deeplink is used - from a logged in and logged out account.
  • If the PR modifies the UI (e.g. new buttons, new UI components, changing the padding/spacing/sizing, moving components, etc) or modifies the form input styles:
    • I verified that all the inputs inside a form are aligned with each other.
    • I added Design label and/or tagged @Expensify/design so the design team can review the changes.
  • For any bug fix or new feature in this PR, I verified that sufficient unit tests are included to prevent regressions in this flow.
  • If the main branch was merged into this PR after a review, I tested again and verified the outcome was still expected according to the Test steps.
  • I have checked off every checkbox in the PR reviewer checklist, including those that don't apply to this PR.

Screenshots/Videos

Screen.Recording.2026-07-14.at.10.43.28.PM.mov

@mjasikowski
mjasikowski removed the request for review from DylanDylann July 20, 2026 09:34
@melvin-bot

melvin-bot Bot commented Jul 20, 2026

Copy link
Copy Markdown

We did not find an internal engineer to review this PR, trying to assign a random engineer to #66387 as well as to this PR... Please reach out for help on Slack if no one gets assigned!

@melvin-bot
melvin-bot Bot requested a review from youssef-lr July 20, 2026 15:29
Replace the ONYXKEYS.DERIVED.ACCOUNT_ID_TO_NAME_MAP derived value (added earlier
on this branch) with a React context provider, following the review direction
that new Onyx derived values are being deprecated. Derived values also can't
hand consumers a stable reference: setDerivedValue writes with
`skipCacheCheck: true`, so every PERSONAL_DETAILS_LIST write re-broadcasts a
fresh map. The provider computes the map in a useMemo instead.

- Add src/hooks/useAccountIDToNameMap.tsx and register the provider in
  AuthScreens ComposeProviders
- Point the five Task pages at the new hook
- Remove the DERIVED.ACCOUNT_ID_TO_NAME_MAP key, config, and type
- Replace the derived-value unit test with a provider/hook test
@hoangzinh
hoangzinh force-pushed the fix/issue-66387-remove-onyx-connect-personal-details-parser branch from 14eef32 to ff71cba Compare August 6, 2026 14:36
@hoangzinh

Copy link
Copy Markdown
Contributor Author

Tested again

image

@hoangzinh

hoangzinh commented Aug 6, 2026

Copy link
Copy Markdown
Contributor Author

@shubham1206agra I updated to use the context provider approach

Comment thread src/hooks/useAccountIDToNameMap.tsx Outdated

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@hoangzinh Maybe use a selector at this point, and can you maybe get this benchmarked first?

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@hoangzinh Bump here

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ah yes, I will look into this today

@hoangzinh hoangzinh Aug 12, 2026

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@shubham1206agra I asked Claude and here is result:

Perf test script
import {AccountIDToNameMapContextProvider, useAccountIDToNameMap} from '@hooks/useAccountIDToNameMap';

import ONYXKEYS from '@src/ONYXKEYS';
import type {PersonalDetails, PersonalDetailsList} from '@src/types/onyx';

import React, {useMemo} from 'react';
import {View} from 'react-native';
// eslint-disable-next-line no-restricted-imports
import Onyx, {useOnyx} from 'react-native-onyx';
import {measureFunction, measureRenders} from 'reassure';

import createPersonalDetails from '../utils/collections/personalDetails';
import waitForBatchedUpdates from '../utils/waitForBatchedUpdates';
import wrapOnyxWithWaitForBatchedUpdates from '../utils/wrapOnyxWithWaitForBatchedUpdates';

// Large-account sizing: TMisiukiewicz noted real customer accounts carry ~18-20k personal details.
const PD_COUNT = 20000;
// Fewer accounts for the render-count comparison - this measures re-render behaviour, not compute scale.
const PD_COUNT_RENDER = 2000;
const CHURN_COUNT = 10;

/** Candidate selector: the same map-building logic, run inside useOnyx's selector. */
function toAccountIDToNameMap(personalDetailsList: PersonalDetailsList | undefined): Record<string, string> {
    const map: Record<string, string> = {};
    for (const personalDetails of Object.values(personalDetailsList ?? {})) {
        if (!personalDetails) {
            continue;
        }
        map[personalDetails.accountID] = personalDetails.login ?? personalDetails.displayName ?? '';
    }
    return map;
}

function buildPersonalDetailsList(count: number): PersonalDetailsList {
    const list: PersonalDetailsList = {};
    for (let i = 1; i <= count; i++) {
        list[String(i)] = createPersonalDetails(i);
    }
    return list;
}

// A monotonic counter guarantees every write sets a brand-new value (so no write is a deep-equal no-op).
let churnCounter = 0;

// Await after each merge so every write flushes as its own broadcast (otherwise sequential merges to
// this single key coalesce into one). This lets measureRenders observe the per-write re-render behaviour.

/** Merge a name-IRRELEVANT field (phoneNumber) so the accountID->name map content is unchanged. */
const writeUnrelatedChanges = async () => {
    for (let i = 1; i <= CHURN_COUNT; i++) {
        churnCounter += 1;
        const patch: PersonalDetailsList = {[i]: {phoneNumber: `irrelevant-${churnCounter}`} as PersonalDetails};
        // eslint-disable-next-line no-await-in-loop
        await Onyx.merge(ONYXKEYS.PERSONAL_DETAILS_LIST, patch);
        // eslint-disable-next-line no-await-in-loop
        await waitForBatchedUpdates();
    }
};

/** Merge a name-RELEVANT field (login) - control: every variant must re-render on these. */
const writeNameChanges = async () => {
    for (let i = 1; i <= CHURN_COUNT; i++) {
        churnCounter += 1;
        const patch: PersonalDetailsList = {[i]: {login: `changed-${churnCounter}@example.com`} as PersonalDetails};
        // eslint-disable-next-line no-await-in-loop
        await Onyx.merge(ONYXKEYS.PERSONAL_DETAILS_LIST, patch);
        // eslint-disable-next-line no-await-in-loop
        await waitForBatchedUpdates();
    }
};

beforeAll(() => Onyx.init({keys: ONYXKEYS}));

beforeEach(() => {
    wrapOnyxWithWaitForBatchedUpdates(Onyx);
});

afterEach(() => Onyx.clear());

describe('useAccountIDToNameMap', () => {
    describe('compute cost (measureFunction)', () => {
        test(`builds the map from ${PD_COUNT} personal details`, async () => {
            const personalDetailsList = buildPersonalDetailsList(PD_COUNT);
            await measureFunction(() => toAccountIDToNameMap(personalDetailsList));
        });
    });

    function SelectorConsumer() {
        const [accountIDToName] = useOnyx(ONYXKEYS.PERSONAL_DETAILS_LIST, {selector: toAccountIDToNameMap});
        return <View testID={String(Object.keys(accountIDToName ?? {}).length)} />;
    }

    function ProviderConsumer() {
        const accountIDToName = useAccountIDToNameMap();
        return <View testID={String(Object.keys(accountIDToName).length)} />;
    }

    function RawConsumer() {
        const [personalDetailsList] = useOnyx(ONYXKEYS.PERSONAL_DETAILS_LIST);
        const accountIDToName = useMemo(() => toAccountIDToNameMap(personalDetailsList), [personalDetailsList]);
        return <View testID={String(Object.keys(accountIDToName).length)} />;
    }

    const providerTree = (
        <AccountIDToNameMapContextProvider>
            <ProviderConsumer />
        </AccountIDToNameMapContextProvider>
    );

    const seed = async () => {
        await Onyx.set(ONYXKEYS.PERSONAL_DETAILS_LIST, buildPersonalDetailsList(PD_COUNT_RENDER));
        await waitForBatchedUpdates();
    };

    // Name-IRRELEVANT churn: the key changes but no name does. The selector's deep-equal cache should
    // keep the consumer from re-rendering; the provider and raw approaches recompute a new reference and re-render.
    describe(`render count on ${CHURN_COUNT} name-irrelevant PERSONAL_DETAILS_LIST writes`, () => {
        test('selector: useOnyx(PERSONAL_DETAILS_LIST, {selector})', async () => {
            await seed();
            await measureRenders(<SelectorConsumer />, {scenario: writeUnrelatedChanges});
        });

        test('context provider: useAccountIDToNameMap()', async () => {
            await seed();
            await measureRenders(providerTree, {scenario: writeUnrelatedChanges});
        });

        test('raw: useOnyx(PERSONAL_DETAILS_LIST) + useMemo', async () => {
            await seed();
            await measureRenders(<RawConsumer />, {scenario: writeUnrelatedChanges});
        });
    });

    // Name-RELEVANT churn (control): every variant must re-render since the map content changes.
    describe(`render count on ${CHURN_COUNT} name-relevant PERSONAL_DETAILS_LIST writes (control)`, () => {
        test('selector: useOnyx(PERSONAL_DETAILS_LIST, {selector})', async () => {
            await seed();
            await measureRenders(<SelectorConsumer />, {scenario: writeNameChanges});
        });

        test('raw: useOnyx(PERSONAL_DETAILS_LIST) + useMemo', async () => {
            await seed();
            await measureRenders(<RawConsumer />, {scenario: writeNameChanges});
        });
    });
});
image image

it seems selector is winner

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@hoangzinh So selector won, right?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

To transform or reshape data without reducing its size — subscribe without a selector and transform inline instead
Ref: https://github.com/Expensify/App/blob/main/.claude/skills/coding-standards/rules/perf-11-optimize-data-selection.md#L22

Yeah, but it violates our rule of using selector in useOnyx hook. I asked Claude to do a perf test on Parser.htmlToMarkdown on both selector and raw inline (which is "transform inline" in our doc). And here is the result:

image

So "transform inline" is the genuine winner here. Should I go with "useOnyx with transform inline" instead?

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@hoangzinh Go ahead

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I updated in 8c89a83

…ountID-to-name map

Switch AccountIDToNameMapContextProvider to a plain useOnyx + useMemo hook.
Benchmarking showed neither the provider nor a useOnyx selector is worth it:

- a selector returning this same-size map runs deepEqual over the whole map on
  every PERSONAL_DETAILS_LIST write (~2.2ms at 20k PDs) and violates PERF-11
- the context provider re-renders consumers on every PD write anyway - same as
  the plain hook - while adding an always-mounted global computation

The hook reads PERSONAL_DETAILS_LIST and reshapes it in a useMemo (no selector).

- Replace src/hooks/useAccountIDToNameMap.tsx (provider) with .ts (hook)
- Remove the provider from AuthScreens ComposeProviders
- Switch the five Task pages to the default-exported hook
- Drop the provider wrapper from the hook unit test
@hoangzinh

hoangzinh commented Aug 13, 2026

Copy link
Copy Markdown
Contributor Author

FAIL tests/unit/SignInBackButtonTest.tsx does not seem related to this PR.

@hoangzinh

Copy link
Copy Markdown
Contributor Author

Looks like we're awaiting your review, @youssef-lr

@youssef-lr
youssef-lr merged commit 2bc342e into Expensify:main Aug 29, 2026
35 of 36 checks passed
@github-actions

Copy link
Copy Markdown
Contributor

🚧 youssef-lr has triggered a test Expensify/App build. You can view the workflow run here.

@OSBotify

Copy link
Copy Markdown
Contributor

✋ This PR was not deployed to staging yet because QA is ongoing. It will be automatically deployed to staging after the next production release.

@OSBotify

Copy link
Copy Markdown
Contributor

🚀 Deployed to staging by https://github.com/youssef-lr in version: 9.4.65-0 🚀

platform result
🕸 web 🕸 success ✅
🤖 android 🤖 success ✅
🍎 iOS 🍎 success ✅

@MelvinBot

Copy link
Copy Markdown
Contributor

No help site changes are required for this PR.

This is an internal refactor with no user-facing behavior change, so nothing under docs/articles needs updating. I did not create a draft PR.

Why

The PR replaces a module-level Onyx.connect on ONYXKEYS.PERSONAL_DETAILS_LIST inside the Parser library with a new useAccountIDToNameMap hook, then threads the resulting accountIDToName map into Parser.htmlToMarkdown calls on the Task pages.

What changed:

  • New hook: src/hooks/useAccountIDToNameMap.ts
  • Call-site updates only: DynamicNewTaskDescriptionPage.tsx, DynamicNewTaskDetailsPage.tsx, DynamicNewTaskTitlePage.tsx, TaskDescriptionPage.tsx, TaskTitlePage.tsx
  • Tests: tests/unit/ParserTest.ts, tests/unit/useAccountIDToNameMapTest.tsx

What did not change:

  • No new or renamed feature, page, tab, setting, or button
  • No copy changes (no src/languages/* edits)
  • No change to what a user sees — task titles and descriptions still render user mentions the same way; only the data-plumbing behind the render changed

Help site articles document product behavior and UI, not internal state-management patterns, so there is nothing here to document.

@hoangzinh, please review the linked help site PR and confirm it reflects the current behavior. Then mark the linked help site PR Ready for review


view run

@OSBotify

OSBotify commented Sep 2, 2026

Copy link
Copy Markdown
Contributor

🚀 Deployed to production by https://github.com/francoisl in version: 9.4.65-3 🚀

platform result
🕸 web 🕸 success ✅
🤖 android 🤖 success ✅
🍎 iOS 🍎 success ✅

Bundle Size Analysis (Sentry):

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

9 participants