Memory Leaks in React Native: Three Heaps, One Staircase

A leak can hide in the JavaScript heap, the native heap or the boundary between them, and each needs a different tool.

Part 1 of 5

Basics

The whole idea first, then the terms the rest of this page uses.

1.1Whole idea

A React Native app has a JavaScript heap, a native heap, and objects that connect the two. A listener that JavaScript never removes can keep a native object alive, and that object keeps a whole screen alive. The telltale sign is memory that climbs one step each time you visit a screen, even after a garbage collection.

Why it matters

A leak can hide in the JavaScript heap, the native heap or the boundary between them, and each needs a different tool.

1.2Key concepts

One idea per card, in plain words.

01JavaScript heap

Objects in the Hermes engine. Leaks here come from listeners, timers and closures that nothing removes.

02Native heap

Java, Kotlin, Swift and C++ objects. A static reference to an Activity or view controller keeps its whole screen alive.

03JSI boundary

Host objects that link the two. A leak on either side can stop the other side from being freed.

04Closure

A function that keeps the variables it uses alive. A listener holding a closure over a large payload keeps the payload.

05Staircase

Memory after forced garbage collection that rises by a fixed amount per screen visit. It is the pattern of a leak.

06Application context

A context that lives as long as the app. Use it for work that doesn't need a screen, and don't hold an Activity for it.

07Retained heap

Memory that garbage collection cannot reclaim because something still points at it. A staircase is the retained heap growing with each visit.

08Anchor

A long-lived object, such as a global event registry, that holds a reference. Everything reachable from it stays alive until the anchor lets go.

09Detached component graph

Components that have unmounted but are still referenced by a closure. A heap snapshot shows them as detached trees that should not exist.

Part 2 of 5

Question

What exactly you must answer, and what to settle before you start.

2.1Question

Interviewer

Crash reports show out-of-memory crashes after about ten minutes of use on mid-range Android. Find the leak and prove it is fixed.

2.2Clarify first

Each answer removes a guess.

You askAnswer
Which screens do users cycle through?A list, a detail screen and a map, repeatedly.
Does memory drop after leaving a screen?Not fully, and it never returns to the starting level.
Part 3 of 5

Detailed answer

How it works, and how to build or explain it.

3.1The picture

Drawn for this page, at a size that reads on a phone.

One leak holding three heapsJavaScript heap (Hermes)listener · timer · closurenever removedJSI boundaryhost objectstill referencedNative heapActivity · view controllernever freedholdsholdsThe screen can't be freed.
A listener nothing removes keeps a host object alive, and the host object keeps a whole screen alive.
Memory after each visit, with and without a leakwarm-upleak: +1.2 MB per visithealthy: flatvisit 1visit 12MBsampled after forcing a garbage collection
Memory after a forced garbage collection, per visit. The first visits are warm-up. After that, a leak climbs and a healthy screen stays flat.

3.2Step by step

The mechanism, in the order you would explain it.

  1. Reproduce with a script

    Open and close the suspect screen many times, forcing a garbage collection after each visit, and record memory.

  2. Read the staircase

    Flat after warm-up means no leak. A steady rise per visit means something stays alive. The code below computes the slope.

  3. Find the heap

    Take a Hermes heap snapshot to look for retained JavaScript objects. Use Android Studio's profiler or Xcode Instruments for native ones.

  4. Follow the retaining path

    Look for the listener, timer or static reference that holds the screen. The snapshot's retainer view shows it.

  5. Fix with cleanup

    Return a cleanup function from every effect that subscribes. Cancel timers and requests. In native code, hold an Activity weakly, or use the application context.

  6. Lock it in

    Add the staircase script to CI for the riskiest screens, and track out-of-memory crash rate in production.

3.3Which layer, which tool

LayerTypical symptomTool
JavaScript heapListeners and state pile upHermes heap snapshots in your React Native debugger
Native heapScreens that never deallocateAndroid Studio Memory Profiler, Xcode Instruments Leaks
JSI boundaryCallbacks and host objects still referencedRetaining paths in a heap dump
ProductionOut-of-memory crash rateCrashlytics or Sentry
Native module on AndroidActivity kept alive after rotation or backMemory Profiler: filter by Activity, then read retained size
iOS objectsCounts that do not return to the pre-navigation levelInstruments: Leaks, and allocations compared by generation

3.4Code

Working code for the core of it.

Finding a staircase, and a listener that never leaves

Memory that rises with each visit to a screen is the mark of a leak. This turns samples into a slope, and shows the listener bug behind many of them.

leak-detector.tsTypeScriptCopy
1/* Finding leaks the way the profiler shows them: memory that climbs one step per screen visit. */2 3/** Least-squares slope of memory against visit number, in MB per visit. */4export function leakSlope(samplesMb: number[]): number {5  const n = samplesMb.length;6  if (n < 2) return 0;7  const meanX = (n - 1) / 2;8  const meanY = samplesMb.reduce((a, b) => a + b, 0) / n;9  let num = 0;10  let den = 0;11  samplesMb.forEach((y, x) => {12    num += (x - meanX) * (y - meanY);13    den += (x - meanX) ** 2;14  });15  return num / den;16}17 18/**19 * Samples are taken after forcing a garbage collection, once per visit. The first visits are warm-up:20 * caches fill and then stop growing, so they are skipped.21 */22export function judgeLeak(samplesMb: number[], opts = { warmup: 2, minVisits: 8, maxMbPerVisit: 0.5 }) {23  const usable = samplesMb.slice(opts.warmup);24  if (usable.length < opts.minVisits) return { leaking: false, slope: 0, verdict: `need ${opts.minVisits} visits after warm-up, got ${usable.length}` };25  const slope = leakSlope(usable);26  const leaking = slope > opts.maxMbPerVisit;27  return { leaking, slope, verdict: leaking ? `grows ${slope.toFixed(2)} MB per visit` : "flat" };28}29 30/** A stand-in for DeviceEventEmitter, so the listener count can be read. */31export class EventHub {32  private listeners = new Map<string, Set<(data: unknown) => void>>();33  on(event: string, fn: (data: unknown) => void) {34    if (!this.listeners.has(event)) this.listeners.set(event, new Set());35    this.listeners.get(event)!.add(fn);36    return { remove: () => this.listeners.get(event)?.delete(fn) };37  }38  emit(event: string, data: unknown) {39    this.listeners.get(event)?.forEach((fn) => fn(data));40  }41  count(event: string) {42    return this.listeners.get(event)?.size ?? 0;43  }44}45 46/** One visit to a screen. Without cleanup, each visit leaves a listener, and its closure, behind. */47export function visitScreen(hub: EventHub, withCleanup: boolean): () => void {48  const subscription = hub.on("sync", () => {});49  return () => {50    if (withCleanup) subscription.remove();51  };52}
52 linesUTF-8TypeScript
samplesMb.slice(opts.warmup)
Caches fill during the first visits. Skipping them stops normal warm-up looking like a leak.
slope > opts.maxMbPerVisit
A steady rise per visit is the signal. Your own limit, from your baseline, goes here.
minVisits
Too few visits can't separate a trend from noise, so the answer is 'not enough data'.
if (withCleanup) subscription.remove()
The leak in one line: without removal, each visit leaves a listener and everything its closure captures.

Tested by npm run test:modules.

3.5Slides

From the source decks this page draws on. Swipe, use the arrows, or press the left and right keys. Notes flag where a slide's numbers or flow differ from this page.

JavaScript heap, JSI host object boundary and native heap shown as three linked layers‹›
1 / 12
Full sizeFull screen

Why a leak crosses all three layers.Slide figures about growth per navigation differ between decks. Use your own slope.

  1. Why a leak crosses all three layers.
  2. How an uncleaned listener turns into an out-of-memory crash.
  3. The three layers of memory in one picture.
  4. Which tool finds a leak in which layer.
  5. The staircase pattern, and the tools that confirm it.
  6. Background tasks leak the same ways, and the cleanup is the same.
  7. Each thread owns a different kind of memory.
  8. How one uncleaned subscription anchors a whole component graph.
  9. The same leak across the native and JSI boundaries.
  10. Which profiler reads which heap, and what to look for.
  11. Three heaps, three causes, three tools.
  12. The staircase, and the effect with no cleanup that draws it.
Part 4 of 5

Q&A

What interviewers ask next. Answer out loud, then open.

4.1Interview questions

Why force a garbage collection before sampling?
Otherwise garbage not yet collected looks like a leak, and a real leak hides in the noise.
Why skip the first visits?
Caches fill and views inflate during warm-up. After that, a healthy screen goes flat.
Why is a leak worse here than in a pure native app?
A reference on one side can keep objects on the other side alive, so a small JavaScript leak can hold a whole native screen.
Activity context or application context?
Application context for anything that doesn't draw. A static Activity reference keeps the old Activity alive across every rotation.
What is the bug in an effect that calls AppState.addEventListener with no return?
The subscription outlives the screen, and so does everything its handler closes over. Keep the returned subscription and call remove() in the cleanup function.
How many navigation cycles make a good leak test?
Enough to get past warm-up and show a slope, such as thirty rapid cycles between two screens, with a forced garbage collection before each reading. Pick a number your CI can run, and keep it fixed.
How can a promise leak across the JSI boundary?
A native module resolves a promise after the component unmounted, and the host object still holds the JavaScript callback. Cancel work on unmount, and let the module drop callbacks it no longer needs.
Why is a WeakReference only a partial fix for Activity leaks?
It stops the strong reference from pinning the Activity, but code can still reach a cleared reference. Avoid holding an Activity at all when the work does not draw anything.
Part 5 of 5

Extra depth

Edge cases, counterpoints and what to read next.

5.1Edge cases and counterpoints

Includes the strongest argument against this approach.

Show detailsHide details
Numbers in the wild
Figures like '10 MB per navigation' appear in articles, and they differ between sources. Your own slope is the only one that counts.
Images
Large bitmaps leak memory without a leak. Size images to their display size and cache by size.
Counterpoint
Not every rise is a leak. A bounded cache grows to its limit and stops, which the flat part after warm-up shows.
Debugger names change
Older guides name Flipper as the heap tool. Current React Native versions use React Native DevTools and the Hermes profiler, so follow your version's documentation.