Skip to content

fix: Prevent "Maximum update depth exceeded" crash when selecting the same workspace while creating consecutive reports - #96720

Merged
JS00001 merged 1 commit into
Expensify:mainfrom
dmkt9:fix/96411
Jul 22, 2026
Merged

fix: Prevent "Maximum update depth exceeded" crash when selecting the same workspace while creating consecutive reports#96720
JS00001 merged 1 commit into
Expensify:mainfrom
dmkt9:fix/96411

Conversation

@dmkt9

@dmkt9 dmkt9 commented Jul 22, 2026

Copy link
Copy Markdown
Contributor

Explanation of Change

  • Use a ref for modalStack to avoid unnecessary changes to the ModalContext.Provider value.
  • This prevents an infinite re-render loop when a component (such as DynamicNewReportWorkspaceSelectionPage) opens a confirmation modal from a useEffect that is triggered by changes to the showModal or closeModal functions from the modal context.

Fixed Issues

$ #96411
PROPOSAL: #96411 (comment)

Tests

Same as QA Steps

  • Verify that no errors appear in the JS console

Offline tests

Same as QA Steps

QA Steps

  1. In Classic Expensify (OldDot), set the personal workspace as the default workspace.
  2. Navigate back to New Expensify.
  3. Click Create Report and select a workspace.
  4. Wait for the empty report to be created.
  5. Click Create Report again.
  6. Ensure the workspace selector opens.
  7. Select the same workspace again.
  8. Verify that the second report should be created successfully using the selected workspace. The application should remain responsive and not encounter any rendering errors.
  • 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 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 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)
  • 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.
  • 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

Android: Native
Android: mWeb Chrome
iOS: Native
iOS: mWeb Safari
MacOS: Chrome / Safari
chrome.mp4

…the same workspace while creating consecutive reports
@dmkt9
dmkt9 requested review from a team as code owners July 22, 2026 08:15
@melvin-bot

melvin-bot Bot commented Jul 22, 2026

Copy link
Copy Markdown

@jayeshmangwani 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]

@melvin-bot
melvin-bot Bot removed request for a team July 22, 2026 08:16
Comment thread src/components/Modal/Global/ModalContext.tsx
@jayeshmangwani

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 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
    • 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
    • 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 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

Android: HybridApp
Android.mov
Android: mWeb Chrome
mweb-chrome.mov
iOS: HybridApp
ios.mov
iOS: mWeb Safari
mweb-safari.mov
MacOS: Chrome / Safari
web.mov

@jayeshmangwani jayeshmangwani left a comment

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.

LGTM 🚀

@melvin-bot
melvin-bot Bot requested a review from JS00001 July 22, 2026 11:31

// We use a ref because `resolveModal` is called on demand, so it doesn't need to re-render whenever `modalStack` changes.
// This keeps the `ModalContext.Provider` value stable and prevents unnecessary updates, avoiding an infinite re-render loop (#96411).
const modalStackRef = useRef(modalStack);

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.

Lets use usePrevious here please

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.

@JS00001 I'm not sure I understand what you mean here. If we use const modalStackPrev = usePrevious(modalStack) and then use modalStackPrev in resolveModal, the issue would still occur because resolveModal would still re-render whenever modalStackPrev changes. Since modalStackPrev changes whenever modalStack changes, I don't think that would solve the problem.

If I've misunderstood your suggestion, please let me know.

Also, if you'd prefer not to use a ref, I have a slightly hacky alternative: wrap the entire resolveModal logic inside the functional updater of setModalStack.

@codecov

codecov Bot commented Jul 22, 2026

Copy link
Copy Markdown

Codecov Report

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

Files with missing lines Coverage Δ
src/components/Modal/Global/ModalContext.tsx 75.60% <75.00%> (+1.92%) ⬆️
... and 9 files with indirect coverage changes

@JS00001

JS00001 commented Jul 22, 2026

Copy link
Copy Markdown
Contributor

@dmkt9

I meant that we have a helper hook for this: usePrevious

Code here:

const modalStackRef = useRef(modalStack);

useEffect(() => {
  modalStackRef.current = modalStack;
}, [modalStack]);

usePrevious implementation:

export default function usePrevious<T>(value: T): T {
    const ref = useRef<T>(value);
    useEffect(() => {
        ref.current = value;
    }, [value]);
    return ref.current;
}

@dmkt9

dmkt9 commented Jul 22, 2026

Copy link
Copy Markdown
Contributor Author

@JS00001 Ah, I understand your suggestion now. You're right that this pattern is repeated in several places. However, I think we need to use the ref itself rather than ref.current, whereas usePrevious returns ref.current.

Would it make sense to introduce a new helper to avoid this repetition? For example:

function useSyncedRef<T>(value: T) {
    const ref = useRef<T>(value);
    useEffect(() => {
        ref.current = value;
    }, [value]);

    return ref;
}

Then we could use it in both places.

@JS00001

JS00001 commented Jul 22, 2026

Copy link
Copy Markdown
Contributor

@dukenv0307 we only use ref.current though:
image

😕

@JS00001

JS00001 commented Jul 22, 2026

Copy link
Copy Markdown
Contributor

So this would just be:

const modalStackValue = usePrevious(modalStack)

...

const lastModalID = modalStackValue.modals.at(...)

@dmkt9

dmkt9 commented Jul 22, 2026

Copy link
Copy Markdown
Contributor Author

So this would just be:

const modalStackValue = usePrevious(modalStack)

...

const lastModalID = modalStackValue.modals.at(...)

Just to make sure I understand correctly: modalStackValue changes whenever modalStack changes, right? If that's the case, resolveModal would still re-render, so I think the issue would still occur.

@JS00001

JS00001 commented Jul 22, 2026

Copy link
Copy Markdown
Contributor

no, because its a ref

@JS00001

JS00001 commented Jul 22, 2026

Copy link
Copy Markdown
Contributor

Its the same code that you've already added in this PR, but its using the helper that already exists for this pattern

@dmkt9

dmkt9 commented Jul 22, 2026

Copy link
Copy Markdown
Contributor Author

no, because its a ref

But modalStackValue is just the previous value of modalStack; it isn't a ref

@JS00001

JS00001 commented Jul 22, 2026

Copy link
Copy Markdown
Contributor

Ah right, you're reading it within a callback so we need .current instead of the stored value, sorry!

@dmkt9

dmkt9 commented Jul 22, 2026

Copy link
Copy Markdown
Contributor Author

Here is the compiled code for resolveModal. As you can see, using usePrevious produces essentially the same compiled code, so the issue would still occur because resolveModal is still recreated whenever modalStackValue changes.

In contrast, this PR ensures that resolveModal never changes when modalStack changes by reading the latest value from a ref instead.

  • Current implementation:
  let t4;
  if ($[3] !== modalStack.modals) {
    t4 = (t5) => {
      const data = t5 === undefined ? { action: ModalActions.CONFIRM } : t5;
      const lastModalId = modalStack.modals.at(-1)?.id;

      if (!lastModalId) {
        return;
      }

      const lastModalPromise = modalPromisesStack.current?.[lastModalId];
      if (lastModalPromise) {
        lastModalPromise.resolve(data);
        delete modalPromisesStack.current[lastModalId];
      }
    };
    $[3] = modalStackValue.modals;
    $[4] = t4;
  } else {
    t4 = $[4];
  }
  const resolveModal = t4;
  • Using usePrevious:
  const modalStackValue = usePrevious(modalStack);
  let t4;
  if ($[3] !== modalStackValue.modals) {
    t4 = (t5) => {
      const data = t5 === undefined ? { action: ModalActions.CONFIRM } : t5;
      const lastModalId = modalStackValue.modals.at(-1)?.id;

      if (!lastModalId) {
        return;
      }

      const lastModalPromise = modalPromisesStack.current?.[lastModalId];
      if (lastModalPromise) {
        lastModalPromise.resolve(data);
        delete modalPromisesStack.current[lastModalId];
      }
    };
    $[3] = modalStackValue.modals;
    $[4] = t4;
  } else {
    t4 = $[4];
  }
  const resolveModal = t4;
  • This PR:
  useEffect(t4, t5);
  let t6;
  if ($[6] === Symbol.for("react.memo_cache_sentinel")) {
    t6 = (t7) => {
      const data = t7 === undefined ? { action: ModalActions.CONFIRM } : t7;
      const lastModalId = modalStackRef.current.modals.at(-1)?.id;

      if (!lastModalId) {
        return;
      }

      const lastModalPromise = modalPromisesStack.current?.[lastModalId];
      if (lastModalPromise) {
        lastModalPromise.resolve(data);
        delete modalPromisesStack.current[lastModalId];
      }
    };
    $[6] = t6;
  } else {
    t6 = $[6];
  }
  const resolveModal = t6;

@JS00001
JS00001 merged commit 7fdf57a into Expensify:main Jul 22, 2026
39 of 40 checks passed
@dmkt9

dmkt9 commented Jul 22, 2026

Copy link
Copy Markdown
Contributor Author

Ah right, you're reading it within a callback so we need .current instead of the stored value, sorry!

No worries at all! Thanks for taking another look.

@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.

@github-actions

Copy link
Copy Markdown
Contributor

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

@OSBotify

Copy link
Copy Markdown
Contributor

🚀 Deployed to staging by https://github.com/JS00001 in version: 9.4.43-0 🚀

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

@MelvinBot

Copy link
Copy Markdown
Contributor

🤖 I reviewed the changes in this PR and no help site documentation updates are required.

Why: This is a purely internal technical fix. The change in src/components/Modal/Global/ModalContext.tsx switches resolveModal to read the modal stack from a useRef instead of state, keeping the ModalContext.Provider value stable to prevent an infinite re-render loop (Expensify/App#96411).

There is no change to any user-facing feature, UI element, tab, setting, label, button, or workflow — so nothing maps to an article under docs/articles. No draft PR was created.

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

@OSBotify

Copy link
Copy Markdown
Contributor

🚀 Deployed to production by https://github.com/yuwenmemon in version: 9.4.43-1 🚀

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.

5 participants