discovering-turbomodules icon indicating copy to clipboard operation
discovering-turbomodules copied to clipboard

A step by step example of creating your own React Native TurboModule.

Discovering Turbo Modules

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.

  1. see commit - Basic initialization and boilerplate (use npx create-react-native-library with C++ template)
  2. see commit - Adding fbjni for Android - it greatly improves Java - C++ interop.
  3. see commit - Migrating from legacy RN bridge to JSI.
  4. see commit - Implementing the "Real" Turbo Module.
  5. see commit - Calling Kotlin/Swift code from C++ module.
  6. 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 - calculates a^2 + b^2 - this method has C++ only implementation
  • makeGreetingFor(name: string): string - returns [Tag] Hello, {name}! - we want this method to be implemented for each platform separately in Kotlin/Swift.

Useful repositories and articles about Turbo Modules:

Known issues

  • In iOS project, after each pod install you have to manually add GreetingManager.swift to project in Xcode. Adding *.swift to podfile sources causes conflicts with React dependencies, because they're not modularized. You could also try with use_frameworks!.

Below is a react-native-builder-bob generated readme:

Installation

npm install my-turbo-utils

Usage

import MyTurboUtils from 'my-turbo-utils';

// 3*3 + 4*4 = 25
const result = await MyTurboUtils.sumSquares(3, 7);

const greeting = await MyTurboUtils.makeGreetingFor('TurboModules');

Contributing

See the contributing guide to learn how to contribute to the repository and the development workflow.

License

MIT