Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Enable React concurrent mode #42592

Merged

Conversation

Kicu
Copy link
Contributor

@Kicu Kicu commented May 24, 2024

Glossary

React concurrent mode

Starting from react 18 we can run React in new concurrent way (which seems the way React team is moving). Concurrent mode enables a lot of new behaviours in react, most importantly renders can be interrupted by React, re-run or run more than once. This is supposed to make react more performant and webapps more responsive to user actions.
State of this in Expensify:

  • on native apps after we migrated new arch and enabled Fabric - to my knowledge - we should already be running react concurrently
  • on web we are running legacy mode and this PR enables concurrent mode

Further reading:

React StrictMode

<StrictMode> is a component that wraps the whole App in (or parts of App) and it runs extra checks and extra behaviors only in dev. So in essence it's a kind of devtool for developers, that should help catch tricky bugs that could be introduced when running concurrent mode. Mainly it renders every component twice (discarding the first render) and runs all effects twice.
This behaviour ☝️ of StrictMode is the source of most bugs that happen to us.

Note: StrictMode is not needed for concurrent react to work but it is much safer to use it.

https://react.dev/reference/react/StrictMode

Details

This PR enables running React 18+ in concurrent mode alongside using StrictMode.
I did not provide screenshots or videos because this affects the whole how React behaves, so in theory affects the whole app.

Done

List of known bugs & fixes

  • react-navigation breaks on StrictMode - fixed via local patch - need to verify the legitness of said patch solved
  • react-native-reanimated
    • animations not working - OS team will fix, we have local patch in the meantime
    • initial animation when entering Report sometimes flickers; this happens because of StrictMode so only in dev

Fixed Issues

$ #33531
PROPOSAL:

Tests

  • Verify that web and native build and run
  • test all the most important features of the app and verify nothing breaks

Offline tests

QA Steps

  • verify that web and native app runs
  • test all the most important features of the app and verify that nothing obvious breaks

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
    • MacOS: Desktop
  • 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 the left part of a conditional rendering a React component is a boolean and NOT a string, e.g. myBool && <MyComponent />.
    • 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
      • If any non-english text was added/modified, I verified the translation was requested/reviewed in #expensify-open-source and it was approved by an internal Expensify engineer. Link to Slack message:
    • 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.js 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 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.
  • 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
MacOS: Desktop

Copy link

melvin-bot bot commented May 24, 2024

Hey! I see that you made changes to our Form component. Make sure to update the docs in FORMS.md accordingly. Cheers!

@@ -40,4 +40,4 @@ function TextInputClearButton({onPressButton}: TextInputClearButtonProps) {

TextInputClearButton.displayName = 'TextInputClearButton';

export default forwardRef(TextInputClearButton);
Copy link
Contributor Author

@Kicu Kicu May 24, 2024

Choose a reason for hiding this comment

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

This is unrelated but a source of warning in browser console - the ref was unused.
While working on updated React I wanted to get rid of as many console warnings as I can since it helps to find the actual React bugs

Copy link
Contributor

Choose a reason for hiding this comment

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

Sounds good, but may I suggest creating a separate PR to remove this ref?

Copy link
Contributor

Choose a reason for hiding this comment

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

Can you please revert this change as it's done in #44155

@Kicu Kicu force-pushed the kicu/concurrent-react-lets-go branch from 8dd4c17 to b3ff01b Compare May 29, 2024 07:03
@Kicu Kicu force-pushed the kicu/concurrent-react-lets-go branch 5 times, most recently from 190c401 to 831a491 Compare June 19, 2024 10:29
@Kicu Kicu changed the title [WIP] Enable React concurrent mode Enable React concurrent mode Jun 19, 2024
@Kicu
Copy link
Contributor Author

Kicu commented Jun 19, 2024

react-navigation status

  • react-navigation in version 6 (current stable) does not work well in StrictMode when using linkingConfig - which we do
  • I created a simple RN app with reproduction of this behaviour and I have tested it using newer v7 version and it works, However react-navigation 7 is still in alpha: https://github.com/react-navigation/react-navigation/releases
  • I asked @satya164 who is an author of react navigation and he said that it is unlikely for this fix to be backported to 6 and suggested we try version 7 - perhaps this is a good idea to try
  • I have found the source of bug in v6 and compared the code to v7 and I was able to prepare a patch for expensify. I can't 100% guarantee at this point that the patch won't break something else, but it feels mostly safe - I only edited one file.

detailed description of patch

The source of problems for us is that inside useNavigationBuilder there is code that cleans state on component unmount here: https://github.com/react-navigation/react-navigation/blob/6.x/packages/core/src/useNavigationBuilder.tsx#L557-L561
Because of StrictMode navigation components will be rendered twice and their effects will run twice. This in turn means that when the navigation renders and runs for the second time, the state is already cleaned from the previous effect cleanup.

Then this check will trigger: https://github.com/react-navigation/react-navigation/blob/6.x/packages/core/src/useNavigationBuilder.tsx#L372 and there is no navigation happening at all.

The patch fixes this in a similar way to v7 branch.

CC @adamgrzybowski @WoLewicki for visibility

@Kicu Kicu force-pushed the kicu/concurrent-react-lets-go branch from 831a491 to 875756f Compare June 20, 2024 08:05
@adamgrzybowski
Copy link
Contributor

As a follow up to @Kicu mentioning react-navigation 7. This version introduces two functionalities that we may be interested in:

  • preload -> We could potentially use it for optimization and performance.
  • popTo -> It may help us with simplifying the UP action implementation.

@Kicu Kicu force-pushed the kicu/concurrent-react-lets-go branch from 875756f to 24fa270 Compare June 20, 2024 10:19
@Kicu Kicu force-pushed the kicu/concurrent-react-lets-go branch from 24fa270 to a2c8d2c Compare June 20, 2024 10:59
@Kicu Kicu marked this pull request as ready for review June 20, 2024 11:00
@Kicu Kicu requested a review from a team as a code owner June 20, 2024 11:00
@melvin-bot melvin-bot bot removed the request for review from a team June 20, 2024 11:00
Copy link

melvin-bot bot commented Jun 20, 2024

@rayane-djouah 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 requested a review from rayane-djouah June 20, 2024 11:00
@Kicu
Copy link
Contributor Author

Kicu commented Jun 20, 2024

@mountiny @roryabraham We're ready for liftoff 🚀

Web and native builds work, there are no crucial issues and app works. Now I think we need some heavy testing by QA's - I tested only the basic functionalities that I know about. If any bugs come up they could be rather tricky or non-obvious.

@WoLewicki
Copy link
Contributor

Maybe we could open another PR with all the changes not strictly related to the StrictMode so they can be also tested and merged earlier if they work properly? This way, this PR would focus only on the StrictMode. And that other PR is merged before this one, you can just merge the newest main here. Wdyt @Kicu ?

@Kicu
Copy link
Contributor Author

Kicu commented Jun 20, 2024

I'm not sure. Technically it will be easy to split this into only concurrent mode and only StrictMode and I could do it, but how much would this really improve the process?
In theory if QA people will test this on production build, then strictmode should not affect it in any way. Per docs:

All of these checks are development-only and do not impact the production build.

So maybe leaving this PR as is will just be simpler?

@jasperhuangg
Copy link
Contributor

jasperhuangg commented Jul 1, 2024

@Kicu @roryabraham I'm having trouble following how this code only runs on dev considering that the USE_REACT_STRICT-MODE flag is always true and isn't dependent on any environment variables. Can you explain?

I'm mainly asking because there's a crash happening here on staging that involves a component exceeding the max update depth.

@jasperhuangg
Copy link
Contributor

Hmm taking a deeper look at the docs it seems there's logic within React's StrictMode implementation that prevents it from running effects twice on staging/production builds.

@Kicu
Copy link
Contributor Author

Kicu commented Jul 2, 2024

@jasperhuangg indeed its the internal behavior of StrictMode, described in the React docs that makes it only work in dev.
https://react.dev/reference/react/StrictMode#enabling-strict-mode-for-entire-app
So I'm trusting react devs here. It should be safe to ship apps wrapped with strict mode to prod and expect strict mode will not do any of the checks.

The CONFIG flag is for the convenience of developers for quick testing locally why their code fails

bondydaa added a commit that referenced this pull request Jul 3, 2024
…current-react-lets-go"

This reverts commit d047467, reversing
changes made to 04f6598.
mountiny added a commit that referenced this pull request Jul 3, 2024
…current-react-lets-go"

This reverts commit d047467, reversing
changes made to 04f6598.
@OSBotify
Copy link
Contributor

OSBotify commented Jul 3, 2024

🚀 Deployed to production by https://github.com/jasperhuangg in version: 9.0.3-7 🚀

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

@OSBotify
Copy link
Contributor

🚀 Deployed to production by https://github.com/Julesssss in version: 9.0.5-13 🚀

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

@ikevin127
Copy link
Contributor

👋 The introduction of StrictMode with this PR created the following dev issue:

The issue was fixed by PR #45559, more details on the proposal here.

@ishpaul777
Copy link
Contributor

👋 The introduction of concurrent mode caused Left hand menu and RHP to not open instantly when opening from link

The issue was fixed by PR #45778

@ahmedGaber93
Copy link
Contributor

👋 The introduction of StrictMode cause this DEV issue #44235 and it fixed here #46483

Strict Mode will unmount then remount component on the first render

React 18 introduces a new development-only check to Strict Mode. This new check will automatically unmount and remount every component

see here

Bad
unmount will set value to true, then remount will not back it to false

const isUnmounted = useRef(false);
useEffect(() => {
  return () => {
      isUnmounted.current = true;
  };
}, []);  

Good
unmount will set value to true, then remount will back it to false

const isUnmounted = useRef(null);
useEffect(() => {
  isUnmounted.current = false; // remount will back value to false
  return () => {
      isUnmounted.current = true;
  };
}, []);  

@@ -53,7 +53,6 @@ const webUpdater = (): PlatformSpecificUpdater => ({
export default function () {
AppRegistry.runApplication(Config.APP_NAME, {
rootTag: document.getElementById('root'),
mode: 'legacy',
Copy link
Contributor

Choose a reason for hiding this comment

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

Coming from #47041, our app has some infinite Lottie animations. In concurrent mode, when the SidebarScreen is suspended (i.e., Suspense feature), it conflicts with these animations, preventing the animation component from rendering. :)

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

Successfully merging this pull request may close these issues.