When you are building your react native Android app, you may encounter the error: heap limit Allocation failed.
Usually, this error occurs when your app is using many libraries and when it’s become larger.
As the error describes, its a heap error where it is not enough to perform the tasks. React-native runs a node service to bundle the libraries. When your library count is larger, the node service will require more memory and at a point, it will throw the above error.
Solution for react-native heap limit allocation failed error
Obviously, if you are not going to cut down your libraries, you will have to increase the heap memory allocation. For this memory-hungry operation, we don’t have an optimized solution. In fact, even if it is efficient in memory, it will take more time than it already is when building the bundles.
So the best option will be to increase the memory size
How to increase the heap memory size?
You can use the following path parameter to increase the heap memory
By invoking the node service manually with the following command we can allow the service to use 8192Mb (8Gb) memory for the node service.
node --max-old-space-size=8192 node_modules/react-native/local-cli/cli.js start
You can use the desired memory which suites your machine which won’t be starving other programmes in case of exponential heap overflow.
For any bundled releases which you use to build .aab or .apk bundles, you can define the values in
project.ext.react = [ // keep the entry file and hermes params nodeExecutableAndArgs: ["node", "--max-old-space-size=8192"] ]
This will provide the build script with the path parameters for the node service.
You can enter the values in the
Bundle React Native code and imagessection under the
export NODE_BINARY=node export NODE_ARGS=--max-old-space-size=8192 export NODE_OPTIONS=--max-old-space-size=8192 ../node_modules/react-native/scripts/react-native-xcode.sh
Finally, always keep an eye on memory usage. React native use memory majorly for the node service and JVM for android builds. Xcode also uses a significant amount of memory. So take special note if you are running your emulators also when building.
Checkout following blog to setup FCM Push Notification with React Native apps.