Note: This example was made in RN 0.63. Some things have changed since then, but the good news is that now the setup should be easier in RN 0.67 / 0.68
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-library
with C++ template) - see commit - Adding
fbjni
for 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 install
you have to manually addGreetingManager.swift
to project in Xcode. Adding*.swift
to 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-utils
import 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