Important
This example was made in RN 0.63. A lot has changed since then; turbo modules and the (new) architecture are now the defaults in modern React Native. Please refer to the official RN documentation for the most up-to-date information.
A journey to discover React Native TurboModules. Alghough TurboModules aren't officially released yet and there is almost no documentation, there are already some libraries based on new infrastructure, including awesome Reanimated 2 by SWM. I digged through React Native source code and various Github repositories to learn how it is done. I managed to get it working, so I share my step-by-step journey here.
Each commit is a different stage towards a fully featured Turbo Module.
- see commit - Basic initialization and boilerplate (use
npx create-react-native-librarywith C++ template) - see commit - Adding
fbjnifor Android - it greatly improves Java - C++ interop. - see commit - Migrating from legacy RN bridge to JSI.
- see commit - Implementing the "Real" Turbo Module.
- see commit - Calling Kotlin/Swift code from C++ module.
- TODO: Multithreading / asynchronous operations (a commit with experiments)
I'm not so creative in examples, I ended up with something simple, but demonstrating: The module consists of two methods:
sumSquares(a: number, b: number): number- calculatesa^2 + b^2- this method has C++ only implementationmakeGreetingFor(name: string): string- returns [Tag] Hello, {name}! - we want this method to be implemented for each platform separately in Kotlin/Swift.
- Reanimated 2
- react-native-multithreading - contains a subset of Reanimated 2 library - may be easier to understand
- react-native-quick-sqlite - JSI based C++ library for sqlite.
- karol-bisztyga/rnfbjni - Android only, probably a minimal TurboModule example
- How to create a react-native JSI module
- In iOS project, after each
pod installyou have to manually addGreetingManager.swiftto project in Xcode. Adding*.swiftto podfile sources causes conflicts with React dependencies, because they're not modularized. You could also try withuse_frameworks!.
Below is a react-native-builder-bob generated readme:
npm install my-turbo-utilsimport MyTurboUtils from 'my-turbo-utils';
// 3*3 + 4*4 = 25
const result = await MyTurboUtils.sumSquares(3, 7);
const greeting = await MyTurboUtils.makeGreetingFor('TurboModules');See the contributing guide to learn how to contribute to the repository and the development workflow.
MIT