Using native code, especially C++, can be an excellent way to enhance your React Native app by leveraging performance-critical logic or existing C++ libraries. This guide will walk you through setting up a C++ library in a React Native project using a development build.
Requirements
Before you start, make sure you have the following:
- React Native CLI installed (since the managed Expo Go app does not support custom native code).
- Development Build configuration for Expo, if you’re using Expo.
- A basic understanding of JNI (Java Native Interface) if you're working with Android, or bridging concepts if you're working with iOS.
Step 1: Set Up Your React Native Project
First, create a new React Native project (if you haven’t already):
npx react-native init MyApp
cd MyApp
For Expo projects, you would need to create a development build. Check Expo’s Development Build Documentation for details.
Step 2: Add Your C++ Library
-
Create a New Folder for Native Code: Inside your project, add a folder for the C++ files, e.g.,
cpp/
. -
Add Your C++ Code: Inside the
cpp/
folder, create a C++ file (e.g.,MyLibrary.cpp
). This file will contain the native code you want to use in React Native.// cpp/MyLibrary.cpp #include
extern "C" JNIEXPORT jint JNICALL Java_com_myapp_MyModule_addNumbers(JNIEnv* env, jobject obj, jint a, jint b) { return a + b; }
Step 3: Configure Android to Use the C++ Library
-
Update
build.gradle
: Add NDK support in your Android project if not enabled. Openandroid/app/build.gradle
and add the following underdefaultConfig
:externalNativeBuild { cmake { cppFlags "-std=c++17" } } ndk { abiFilters "armeabi-v7a", "arm64-v8a", "x86", "x86_64" // Customize as needed }
-
Configure CMake: Create a
CMakeLists.txt
file in your project’s root directory or thecpp/
directory.# CMakeLists.txt cmake_minimum_required(VERSION 3.4.1) add_library( # Sets the name of the library. mylibrary # Sets the library as a shared library. SHARED # Provides the relative path to your source file(s). cpp/MyLibrary.cpp ) find_library( # Sets the path to the log library. log-lib log ) target_link_libraries( # Links your native library with the log library. mylibrary ${log-lib} )
-
Update Android Native Code Bridge: To expose this method to JavaScript, create a native module. Add a new file,
MyModule.java
, inandroid/app/src/main/java/com/myapp/
:// android/app/src/main/java/com/myapp/MyModule.java package com.myapp; import androidx.annotation.NonNull; import com.facebook.react.bridge.ReactContextBaseJavaModule; import com.facebook.react.bridge.ReactMethod; import com.facebook.react.bridge.Promise; public class MyModule extends ReactContextBaseJavaModule { static { System.loadLibrary("mylibrary"); // Loads the C++ library } @NonNull @Override public String getName() { return "MyModule"; } @ReactMethod public void addNumbers(int a, int b, Promise promise) { promise.resolve(addNumbersJNI(a, b)); } public native int addNumbersJNI(int a, int b); }
Register the module in
MainApplication.java
undergetPackages
to ensure React Native can use it.
Step 4: Write the JavaScript Bridge
-
In your React Native code, create a JavaScript file to wrap the native module:
// MyModule.js import { NativeModules } from 'react-native'; const { MyModule } = NativeModules; export const addNumbers = (a, b) => MyModule.addNumbers(a, b);
-
Now, you can use
addNumbers
in your React Native code:import React, { useState } from 'react'; import { Button, Text, View } from 'react-native'; import { addNumbers } from './MyModule'; const App = () => { const [result, setResult] = useState(null); const handleAddNumbers = async () => { const sum = await addNumbers(5, 10); setResult(sum); }; return (
{result && ); }; export default App;Result: {result} }
Step 5: Build and Run Your App
Finally, you need to rebuild the Android project to link the native code:
cd android
./gradlew clean
cd ..
npx react-native run-android
If using Expo with development builds, make sure your build reflects these changes. For more details, refer to Expo’s Development Builds documentation.
With this setup, you’ve successfully integrated a C++ library in your React Native project, enabling you to call native C++ functions directly from JavaScript. This opens up possibilities for using optimized C++ code, accessing hardware-accelerated libraries, or reusing existing C++ code in your React Native app.