Memory leaks in Flutter and React Native happen when your app keeps references to objects it no longer needs. These could be controllers, timers, listeners or subscriptions that remain active even after a screen is closed.
The result? Increasing memory usage, sluggish performance, UI freezes and unexpected crashes.
The fix often comes down to one simple rule:
Whatever a screen starts, it must stop or dispose of when that screen goes away.
In this guide, we'll explore how to identify memory leaks in Flutter and React Native, use Android debugging tools, and prevent common lifecycle-related issues.
What Is a Memory Leak in a Mobile App?
Garbage collection removes objects that are no longer referenced by an application.
A memory leak occurs when a long-lived object, such as a global variable, timer or subscription, continues referencing something that should have been removed.
Common Examples of Memory Leaks
- A screen closes, but its event listener remains registered.
- A timer continues running after its component is removed.
- A stream or event subscription is never cancelled.
- A singleton keeps a reference to an Activity, screen or BuildContext.
Memory Leak vs. Memory Bloat
| Memory Leak | Memory Bloat |
|---|---|
| Memory usage keeps increasing over repeated actions. | Memory usage is high but relatively stable. |
| Objects remain referenced unnecessarily. | Large resources consume excessive memory. |
| Requires proper cleanup and lifecycle management. | Often requires resource optimisation. |
| Can eventually cause crashes. | Can slow down application performance. |
What Are the Signs of a Memory Leak?
Watch out for these warning signs:
- Memory usage increases every time you open and close the same screen.
- Screen transitions become progressively slower.
- The UI starts stuttering or freezing during long sessions.
- Android kills the application more frequently.
-
OutOfMemoryErrorappears in Logcat.
What Usually Causes Memory Leaks in Flutter and React Native?
Here are five common causes:
- Unremoved listeners: Scroll, keyboard and app-state listeners remain active.
-
Uncancelled timers:
Timer.periodicorsetIntervalcontinues running unnecessarily. - Open subscriptions: Streams, observers and event emitters are never cancelled.
- Unnecessary references: Globals and singletons retain references to screens or their state.
- Large images and data: Excessive resource consumption increases memory pressure.
Most of these problems come down to poor lifecycle management.
How to Find and Fix Memory Leaks in Flutter
1. Compare Heap Snapshots Using Flutter DevTools
Flutter DevTools provides useful memory profiling features:
- Profile Memory: View current memory allocation by class.
- Diff Snapshots: Compare memory usage before and after an action.
- Trace Instances: Identify where objects were allocated.
Steps to identify a leak:
- Run your application on an Android device or emulator.
- Open Flutter DevTools and navigate to the Memory tab.
- Select Diff Snapshots.
- Capture a snapshot before opening the suspected screen.
- Open and close that screen five or six times.
- Capture another snapshot and compare the results.
- Check whether instances of the screen's State, controllers or custom classes continue increasing.
Use Trace Instances to investigate where those objects were created.
Reference: Flutter DevTools Memory View.
2. Dispose Controllers in StatefulWidget
A common Flutter mistake is creating a controller without disposing of it.
Incorrect approach:
class _LoginScreenState extends State<LoginScreen> {
final controller = TextEditingController();
@override
Widget build(BuildContext context) {
return TextField(controller: controller);
}
}
Correct approach:
class _LoginScreenState extends State<LoginScreen> {
final controller = TextEditingController();
@override
void dispose() {
controller.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return TextField(controller: controller);
}
}
Apply the same principle to AnimationController, ScrollController, FocusNode and other disposable objects.
Remember: If your State creates an object, your State should dispose of it.
3. Cancel Stream Subscriptions
Uncancelled subscriptions can retain references to the widget's State.
import 'dart:async';
class _PriceTickerState extends State<PriceTicker> {
late final StreamSubscription<double> _subscription;
double _latest = 0;
@override
void initState() {
super.initState();
_subscription = widget.prices.listen((price) {
setState(() => _latest = price);
});
}
@override
void dispose() {
_subscription.cancel();
super.dispose();
}
@override
Widget build(BuildContext context) => Text('$_latest');
}
Calling cancel() ensures the subscription no longer retains the screen through its callback.
4. Avoid Storing BuildContext in Long-Lived Objects
Storing BuildContext inside a singleton, service or long-running callback can keep the widget tree reachable.
Instead, retrieve the required values inside build() and pass those values to other objects.
5. Detect Undisposed Objects Through Widget Tests
Flutter developers can use the leak_tracker_flutter_testing package to detect objects that are created but never disposed of.
Add leak tracking to your widget tests and follow the package's current documentation for setup.
How to Find and Fix Memory Leaks in React Native
React Native applications have two memory areas to consider:
- JavaScript heap (Hermes): Stores components, state, closures and timers.
- Native Android heap: Stores views, bitmaps and native modules.
Both require separate debugging approaches.
1. Take JavaScript Heap Snapshots in React Native DevTools
React Native 0.76 and later, when using Hermes, includes a Memory panel in React Native DevTools.
Follow these steps:
- Start Metro and press
jto open React Native DevTools. - Navigate to the Memory panel.
- Capture an initial heap snapshot.
- Open and close the suspected screen several times.
- Capture another snapshot.
- Switch to Comparison view.
- Search for component or class names and inspect the Retainers section.
Objects whose count continues increasing with every visit may indicate a memory leak.
Reference: React Native DevTools.
2. Check Native Memory Using Android Studio Profiler
Use Android Studio Profiler when investigating native memory issues.
Steps:
- Open your project's
android/folder in Android Studio. - Run the application in debuggable mode.
- Select Track Memory Consumption to monitor Java/Kotlin allocations.
- Alternatively, choose Analyze Memory Usage to capture a heap dump.
- Inspect activity or fragment leaks and duplicate bitmaps.
Remember that JavaScript leaks may not appear as named objects in the native heap. Start with React Native DevTools when investigating component-level issues.
3. Always Return a Cleanup Function from useEffect
Incorrect approach:
useEffect(() => {
const interval = setInterval(() => {
console.log("Running...");
}, 1000);
}, []);
Correct approach:
useEffect(() => {
const interval = setInterval(() => {
console.log("Running...");
}, 1000);
return () => clearInterval(interval);
}, []);
The cleanup function runs when the component unmounts and before the effect runs again when its dependencies change.
4. Remove Event Listeners
Always remove listeners when they are no longer required.
useEffect(() => {
const subscription = AppState.addEventListener(
'change',
handleAppStateChange
);
return () => subscription.remove();
}, []);
5. Cancel Unnecessary Network Requests
Use AbortController to prevent unnecessary requests from continuing after a component is removed or its URL changes.
useEffect(() => {
const controller = new AbortController();
fetch(url, { signal: controller.signal })
.then((res) => res.json())
.then(setData)
.catch((err) => {
if (err.name !== 'AbortError') {
setError(err);
}
});
return () => controller.abort();
}, [url]);
This prevents an outdated request from updating a screen the user has already left.
Flutter vs React Native: Memory Leak Debugging Compared
| Debugging Area | Flutter | React Native |
|---|---|---|
| Main memory tool | Flutter DevTools | React Native DevTools |
| Native memory checks | Android Studio Profiler | Android Studio Profiler |
| Snapshot comparison | Diff Snapshots | Comparison View |
| Common culprit | Undisposed controllers and subscriptions | Missing useEffect cleanup |
| Cleanup method | dispose() |
useEffect cleanup function |
| Testing support | leak_tracker | Manual snapshot checks |
How to Prevent Memory Leaks in Mobile Applications
Prevention is easier than debugging a memory problem after release.
Follow these practical habits:
- Pair every start with a stop: Every timer, listener and subscription needs a cleanup method.
- Dispose what you create: Clean up controllers, focus nodes and animation objects.
- Avoid unnecessary global references: Keep screen-specific objects out of singletons.
- Optimise image sizes: Avoid loading full-resolution images for small thumbnails.
- Test repeated navigation: Open and close important screens 10–20 times.
- Test on low-RAM devices: Smaller devices can expose issues that flagship phones hide.
- Stop background activities: Cancel unnecessary polling, timers and background tasks.
Frequently Asked Questions
Does garbage collection prevent memory leaks?
No. Garbage collection only removes objects that are no longer referenced. If an active reference remains, the object stays in memory.
How can I distinguish a memory leak from normal memory growth?
Repeat the same action several times. Normal memory usage generally stabilises, while a leak continues increasing without returning to a stable level.
Is Android Studio Profiler enough for React Native?
Not always. Android Studio Profiler is useful for native memory, while React Native DevTools helps identify JavaScript heap leaks.
Do all Flutter controllers need to be disposed of?
Disposable objects created and owned by your State should be disposed of. If a parent provides the controller, the parent is responsible for its lifecycle.
The One Rule Every Mobile Developer Should Remember
Memory leaks rarely appear immediately. They build up quietly during long application sessions, making them easy to overlook during basic testing.
Take heap snapshots, inspect retained objects, test repeated navigation and clean up every resource properly.
If you start something, know exactly where it stops.
Written by Solitaire Infosystems, a software development company in Mohali that builds software solutions and provides practical IT training, industrial training and internship programmes.
Learn. Build. Debug. Develop better applications with Solitaire Infosystems.
Top comments (0)