CodeBlanks Logo Icon CodeBlanks

TurboModules

Learn TurboModules and JSI-based modules.

What are TurboModules?

TurboModules are native modules bound to the JS side through JSI. They replace the old NativeModules; modules are loaded lazily, on demand.

A TurboModule is defined by a TypeScript spec file and registered with TurboModuleRegistry.getEnforcing. Codegen produces the C++/Java/Objective-C skeleton from this spec.

The spec file

The TurboModule spec file is a .ts file. It defines an interface extending TurboModule; each method's signature is written there. Codegen reads this file.

The file name should follow Native<Name>.ts; e.g. NativeMath.ts. It usually lives at src/NativeMath.ts.

Practice Write the TurboModule spec

Write a TurboModule spec file named NativeMath.ts. Define a Spec interface extending TurboModule with a method add(a: number, b: number): number. Export it with export.

Starter code

App.js
import type { TurboModule } from 'react-native/Libraries/TurboModule/RCTExport';

// Define the Spec interface here

export default TurboModuleRegistry.getEnforcing<Spec>('Math');

Sample solution

App.js
import type { TurboModule } from 'react-native/Libraries/TurboModule/RCTExport';
import { TurboModuleRegistry } from 'react-native';

export interface Spec extends TurboModule {
  add(a: number, b: number): number;
}

export default TurboModuleRegistry.getEnforcing<Spec>('Math');

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Write the TurboModule registration call

Question
const Module = TurboModuleRegistry.____('MyModule');
Answer
const Module = TurboModuleRegistry.getEnforcing('MyModule');

Explanation: getEnforcing returns the module or throws.

2 Match the TurboModule pieces

Term Meaning
Spec file TypeScript interface
getEnforcing Fetches module
Codegen Generates C++ skeleton
NativeModules Old system

3 When are TurboModules loaded?

  • On demand (lazy)
  • All at app startup
  • Only in release builds
  • Only on iOS Correct answer

Explanation: TurboModules are loaded lazily on first call.

All lessons in Expert