Optimizing React Native with C++

Introduction to Native Modules

Native modules in React Native are essential components that allow developers to execute code on a device that isn’t written in JavaScript. These modules act as containers for related native code, and they must be discoverable by an app during both the build and runtime phases. Utilizing native modules can enable tighter platform integration, such as accessing device peripherals and building performance-oriented code that is platform-independent.

Developers can write native module code in various languages including Kotlin, Java, Swift, Objective-C, C++, and Rust. Each of these languages offers unique benefits, with C++ and Rust being particularly notable for their ability to create platform-independent, high-performance code.

Challenges and Trade-offs of Using C++

While C++ can offer increased performance, it is not without its challenges. It can lead to increased build times and lacks the hot reloading capabilities of JavaScript, resulting in a slower development cycle. Additionally, C++ can cause more complex failures and crashes, which are harder to debug due to the lack of clear stack traces.

Managing package dependencies between your JavaScript and C++ code can also be cumbersome, and there’s a steeper learning curve associated with C++. This combination of factors can lower developer productivity. However, like many aspects of software development, these challenges are a trade-off that may be worthwhile depending on the project’s needs.

Understanding React Native Architectures

The evolution of React Native architectures plays a crucial role in how native modules are developed. The old architecture relied heavily on a bridge for message parsing, which led to increased memory usage and inefficient handling of binary data. This architecture has influenced the design of early native modules.

The new architecture introduces the JavaScript Interface (JSI), which abstracts over JavaScript engines like JavaScriptCore and Hermes. JSI allows native modules to interact more directly with the JavaScript runtime, offering a more efficient and streamlined process. The public API of the runtime is straightforward, providing functionalities to evaluate JavaScript, manage microtasks, and access global objects.

Criteria for Choosing Native Module Alternatives

When deciding on the best alternative for building native modules, two main criteria should be considered. First, decide whether to support the old, new, or both architectures. Supporting the old architecture may require additional testing and bug fixes, while focusing on the new architecture simplifies maintenance but may limit user availability.

Second, assess the need for strong typing between JavaScript and native code. Strong typing can reduce catastrophic failures and ease maintenance by keeping both sides in sync. Various approaches exist for code generation, ranging from generating TypeScript declarations from C++ code to creating stubs in TypeScript or Flow for native implementation.

Exploring Native Module Alternatives

The primary alternatives for native modules include TurboNativeModules, LegacyNativeModules, and NitroModules. TurboNativeModules require the new architecture and achieve type safety through code generation from TypeScript or Flow declarations. However, pure C++ modules aren't yet supported on iOS.

LegacyNativeModules do not provide type safety and predate JSI, making it challenging to access the JSI runtime pointer. A hybrid approach combines Legacy and Turbo modules, easing the transition to the new architecture by allowing for implementation switching at build time.

NitroModules: The New Contender

NitroModules are a recent addition, offering significant performance improvements in benchmarks. They support multiple languages and architectures, providing more expressive code generation capabilities. While they require a peer dependency for app developers, this drawback is expected to be resolved in the future.

Practical Considerations for Building with C++

Developers should consider pre-building portions of their native code to reduce build times and complexity for library users. Pre-building allows for earlier detection of type failures and simplifies the build process. However, caution is advised when accessing React Native APIs from pre-builds due to unstable ABI boundaries across versions.

Compiler caches can also be employed to speed up subsequent compilations. On Android, this involves modifying the CMakeList file, while on iOS, a pull request has simplified the process through the use of C cache.

Final Thoughts

NitroModules represent a promising direction for developers looking to leverage C++ in their React Native projects. For complex projects, pre-building can be a valuable strategy, provided developers are mindful of the associated limitations. Utilizing compiler caches can further enhance efficiency, making the development process smoother and more productive.

Watch full talk with demos and examples:

Watch video on a separate page
Rate this content
Bookmark

This talk has been presented at React Summit US 2024, check out the latest edition of this React Conference.

FAQ

C++ native modules can lead to increased build times, complex dependency management, and a higher learning curve, potentially lowering developer productivity.

A native module in React Native is a container of related native code that is discoverable by the app during build and runtime, enabling deeper platform integration.

Building a C++ native module allows for platform-independent performance code, although it comes with challenges like increased build times and a higher learning curve.

The new architecture in React Native includes the JavaScript Interface (JSI), which improves interaction with JavaScript engines and enables more efficient native module design.

JSI, or JavaScript Interface, is an abstraction over JavaScript engines that allows React Native to interact with C++ modules, enhancing performance and integration.

NitroModules are a recent innovation supporting C++, Swift, and Kotlin; they offer expressive code generation and support both old and new React Native architectures.

Pre-building native code reduces build time and complexity for library users, allowing type failures to be caught during development rather than on user machines.

React Native APIs should be avoided in pre-builds because the ABI is not stable across React Native versions, which could lead to compatibility issues.

The recommended approach is to use NitroModules for complex C++ projects, consider pre-builds to reduce build times, and use a compiler cache to speed up compilation.

Cain Hansen works for MongoDB, building developer tools and maintaining a React Native library for the mobile database Realm.

Kræn Hansen
Kræn Hansen
17 min
22 Nov, 2024

Comments

Sign in or register to post your comment.

Check out more articles and videos

We constantly think of articles and videos that might spark Git people interest / skill us up or help building a stellar career

Raising the Bar: Our Journey Making React Native a Preferred Choice
React Advanced 2023React Advanced 2023
29 min
Raising the Bar: Our Journey Making React Native a Preferred Choice
Watch video: Raising the Bar: Our Journey Making React Native a Preferred Choice
This Talk discusses Rack Native at Microsoft and the efforts to improve code integration, developer experience, and leadership goals. The goal is to extend Rack Native to any app, utilize web code, and increase developer velocity. Implementing web APIs for React Native is being explored, as well as collaboration with Meta. The ultimate aim is to make web code into universal code and enable developers to write code once and have it work on all platforms.
Opensource Documentation—Tales from React and React Native
React Finland 2021React Finland 2021
27 min
Opensource Documentation—Tales from React and React Native
Documentation is often your community's first point of contact with your project and their daily companion at work. So why is documentation the last thing that gets done, and how can we do it better? This talk shares how important documentation is for React and React Native and how you can invest in or contribute to making your favourite project's docs to build a thriving community
Bringing React Server Components to React Native
React Day Berlin 2023React Day Berlin 2023
29 min
Bringing React Server Components to React Native
Top Content
Watch video: Bringing React Server Components to React Native
React Server Components (RSC) offer a more accessible approach within the React model, addressing challenges like big initial bundle size and unnecessary data over the network. RSC can benefit React Native development by adding a new server layer and enabling faster requests. They also allow for faster publishing of changes in mobile apps and can be integrated into federated super apps. However, implementing RSC in mobile apps requires careful consideration of offline-first apps, caching, and Apple's review process.
React Native Kotlin Multiplatform Toolkit
React Day Berlin 2022React Day Berlin 2022
26 min
React Native Kotlin Multiplatform Toolkit
Top Content
The Talk discusses the combination of React Native and Kotlin Multiplatform for cross-platform app development. Challenges with native modules in React Native are addressed, and the potential improvements of using Kotlin Multiplatform Mobile are explored. The integration of Kotlin Multiplatform with React Native streamlines native implementation and eliminates boilerplate code. Questions about architecture and compatibility, as well as the possibility of supporting React Native Web, are discussed. The React Native toolkit works with native animations and has potential for open-source development.
Building Cross-Platform Component Libraries for Web and Native with React
React Advanced 2021React Advanced 2021
21 min
Building Cross-Platform Component Libraries for Web and Native with React
Top Content
This Talk discusses building cross-platform component libraries for React and React Native, based on a successful project with a large government-owned news organization. It covers the requirements for React Native knowledge, building cross-platform components, platform-specific components, styling, and the tools used. The Talk also highlights the challenges of implementing responsive design in React Native.
MDX in React-Native!?
React Advanced 2021React Advanced 2021
21 min
MDX in React-Native!?
Top Content
This Talk is about the development of MDX, a combination of Markdown and JSX, by a freelance full stack JavaScript developer. MDX is a powerful technology that allows for the creation of interactive content within blog posts and supports React components. The speaker developed RnMDX, a proper and polished MDX library for React Native, which can be dropped into any React Native app. RnMDX provides solutions for common issues with Markdown content in React Native and allows for the rendering of MDX content into native views. Bringing MDX into native apps is now easier, and it can be used for various purposes, such as serving the app layout from a CMS or creating interactive online magazines or blogs.

Workshops on related topic

Introducing FlashList: Let's build a performant React Native list all together
React Advanced 2022React Advanced 2022
81 min
Introducing FlashList: Let's build a performant React Native list all together
Top Content
WorkshopFree
David Cortés Fulla
Marek Fořt
Talha Naqvi
3 authors
In this workshop you’ll learn why we created FlashList at Shopify and how you can use it in your code today. We will show you how to take a list that is not performant in FlatList and make it performant using FlashList with minimum effort. We will use tools like Flipper, our own benchmarking code, and teach you how the FlashList API can cover more complex use cases and still keep a top-notch performance.You will know:- Quick presentation about what FlashList, why we built, etc.- Migrating from FlatList to FlashList- Teaching how to write a performant list- Utilizing the tools provided by FlashList library (mainly the useBenchmark hook)- Using the Flipper plugins (flame graph, our lists profiler, UI & JS FPS profiler, etc.)- Optimizing performance of FlashList by using more advanced props like `getType`- 5-6 sample tasks where we’ll uncover and fix issues together- Q&A with Shopify team
Detox 101: How to write stable end-to-end tests for your React Native application
React Summit 2022React Summit 2022
117 min
Detox 101: How to write stable end-to-end tests for your React Native application
Top Content
WorkshopFree
Yevheniia Hlovatska
Yevheniia Hlovatska
Compared to unit testing, end-to-end testing aims to interact with your application just like a real user. And as we all know it can be pretty challenging. Especially when we talk about Mobile applications.
Tests rely on many conditions and are considered to be slow and flaky. On the other hand - end-to-end tests can give the greatest confidence that your app is working. And if done right - can become an amazing tool for boosting developer velocity.
Detox is a gray-box end-to-end testing framework for mobile apps. Developed by Wix to solve the problem of slowness and flakiness and used by React Native itself as its E2E testing tool.
Join me on this workshop to learn how to make your mobile end-to-end tests with Detox rock.
Prerequisites- iOS/Android: MacOS Catalina or newer- Android only: Linux- Install before the workshop
How to Build an Interactive “Wheel of Fortune” Animation with React Native
React Summit Remote Edition 2021React Summit Remote Edition 2021
60 min
How to Build an Interactive “Wheel of Fortune” Animation with React Native
Top Content
Workshop
Oli Bates
Oli Bates
- Intro - Cleo & our mission- What we want to build, how it fits into our product & purpose, run through designs- Getting started with environment set up & “hello world”- Intro to React Native Animation- Step 1: Spinning the wheel on a button press- Step 2: Dragging the wheel to give it velocity- Step 3: Adding friction to the wheel to slow it down- Step 4 (stretch): Adding haptics for an immersive feel
Deploying React Native Apps in the Cloud
React Summit 2023React Summit 2023
88 min
Deploying React Native Apps in the Cloud
WorkshopFree
Cecelia Martinez
Cecelia Martinez
Deploying React Native apps manually on a local machine can be complex. The differences between Android and iOS require developers to use specific tools and processes for each platform, including hardware requirements for iOS. Manual deployments also make it difficult to manage signing credentials, environment configurations, track releases, and to collaborate as a team.
Appflow is the cloud mobile DevOps platform built by Ionic. Using a service like Appflow to build React Native apps not only provides access to powerful computing resources, it can simplify the deployment process by providing a centralized environment for managing and distributing your app to multiple platforms. This can save time and resources, enable collaboration, as well as improve the overall reliability and scalability of an app.
In this workshop, you’ll deploy a React Native application for delivery to Android and iOS test devices using Appflow. You’ll also learn the steps for publishing to Google Play and Apple App Stores. No previous experience with deploying native applications is required, and you’ll come away with a deeper understanding of the mobile deployment process and best practices for how to use a cloud mobile DevOps platform to ship quickly at scale.
Effective Detox Testing
React Advanced 2023React Advanced 2023
159 min
Effective Detox Testing
Workshop
Josh Justice
Josh Justice
So you’ve gotten Detox set up to test your React Native application. Good work! But you aren’t done yet: there are still a lot of questions you need to answer. How many tests do you write? When and where do you run them? How do you ensure there is test data available? What do you do about parts of your app that use mobile APIs that are difficult to automate? You could sink a lot of effort into these things—is the payoff worth it?
In this three-hour workshop we’ll address these questions by discussing how to integrate Detox into your development workflow. You’ll walk away with the skills and information you need to make Detox testing a natural and productive part of day-to-day development.
Table of contents:
- Deciding what to test with Detox vs React Native Testing Library vs manual testing- Setting up a fake API layer for testing- Getting Detox running on CI on GitHub Actions for free- Deciding how much of your app to test with Detox: a sliding scale- Fitting Detox into you local development workflow
Prerequisites
- Familiarity with building applications with React Native- Basic experience with Detox- Machine setup: a working React Native CLI development environment including either Xcode or Android Studio
Bringing Your Web App to Native With Capacitor
JSNation 2023JSNation 2023
111 min
Bringing Your Web App to Native With Capacitor
WorkshopFree
Mike Hartington
Mike Hartington
So, you have a killer web app you've built and want to take it from your web browser to the App Store. Sure, there are a lot of options here, but most will require you to maintain separate apps for each platform. You want your codebase to be as close as possible across Web, Android, and iOS. Thankfully, with Capacitor, you can take your existing web app and quickly create native iOS and Android apps for distribution on your favorite App Store!
Contents: This workshop is aimed at beginner developers that have an existing web application, or are interested in mobile development. We will go over:- What is Capacitor- How does it compare to other cross-platform solutions- Using Capacitor to build a native application using your existing web code- Tidying up our application for distribution on mobile app stores with naming conventions, icons, splash screens and more