react-navigation / react-navigation

Routing and navigation for your React Native apps
https://reactnavigation.org
23.3k stars 4.97k forks source link

Navigate into page, increase RAM, navigate back and RAM stays high #11919

Open spagrhetti opened 1 month ago

spagrhetti commented 1 month ago

Current behavior

I'm having issues in my app where I navigate to a page, the RAM usage increases, then I navigate back, expecting the memory consumption to go back down, but the RAM usage stays high.

Here is a repo where I provide a reproducible example: https://github.com/spagrhetti/performance-debugging

The basic setup is this:

  1. My app has two screens, screen A and screen B, both screens in a React Navigation Stack Navigator. We start on screen A.
  2. Navigate to screen B. Screen B has a button that adds a giant string to a useState array. Do this however much you want, after 2 presses RAM usage goes up from ~100MB to about ~850MB on my device (iphone 12 mini).
  3. Navigate back to screen A. I would expect memory to go back down, but it stays at that ~850MB level. Additionally, here is a video of the test: https://www.youtube.com/shorts/ubiYwzrlaQw

Am I missing something? Is there any way to achieve the desired behavior of having RAM go down after navigating back?

I've asked chatGPT about this and it basically tells me that garbage collection in javascript is hard to predict and maybe somehow that memory will get freed later. However, I think that variations of this behavior are causing my app to steadily use more and more RAM as I navigate around, eventually causing it to crash.

Any help on understanding why this occurs and how to better handle memory when dealing with React Navigation would be greatly appreciated!

Note: I notice similar behavior without any navigation involved: allocating a big state var, then setting it to null, RAM usage stays high. I don't completely understand this -- my guess is that I just have to wait for garbage collection to kick in and eventually bring RAM usage back down. However, in my app, that never seems to happen, it just keeps going up and eventually it crashes.

Expected behavior

I would expect RAM to go back down after navigating back to page A.

Reproduction

https://github.com/spagrhetti/performance-debugging

Platform

Packages

Environment

package version
@react-navigation/native 6.1.17
@react-navigation/stack 6.3.29
react-native-safe-area-context 4.8.2
react-native-screens 3.29.0
react-native 0.73.6
expo 50.0.14
node 16.20.1
npm or yarn 8.19.4
trandinhduc commented 1 month ago

I have the same issue here. Our app starts with 200M and just navigate to screen A and goBack and navigate again one more time, it's got 900M RAM, that crazy with just 2 screens.