Memory Leaks - jellyfish-tom/TIL GitHub Wiki

In JavaScript memory is managed automatically by Garbage Collector (GC). In short, Garbage Collector is a background process that periodically traverses the graph of allocated objects and their references. If it happens to encounter a part of the graph that is not being referenced directly or indirectly from root objects (e.g., variables on the stack or a global object like window or navigator) that whole part can be deallocated from the memory.

In React Native world each JS module scope is attached to a root object. Many modules, including React Native core ones, declare variables that are kept in the main scope (e.g., when you define an object outside of a class or function in your JS module). Such variables may retain other objects and hence prevent them from being garbage collected.

Some Causes of Memory Leak:

Unreleased timers/listeners added in componentDidMount Closure scope leaks Detecting memory leaks for IOS:

In Xcode,

Go to XCode → Product → Profile (⌘ + i)

After that shows you all templates choose leaks.

Detecting memory leaks for Android :

Run React Native app normally (react-native run-android) Run Android Studio

On the menu, click Tools → Android → Enable ADB Integration Click Tools → Android → Android Device Monitor When Android Device Monitor shows up, click Monitor → Preferences

There is also one more way in Android Perf Monitor (Performance Monitor) is a good choice to use for android leak monitoring.

Import PerfMonitor from 'react-native/Libraries/Performance/RCTRenderingPerf';

  PerfMonitor.toggle();
  PerfMonitor.start();
  setTimeout(() => {
       PerfMonitor.stop();
    }, 20000);
  }, 5000);