Native modules and the New Architecture
Why it matters
- The New Architecture has been the default since React Native 0.76, and from 0.82 it is the only architecture, so every new native module you write is a Turbo Native Module.
- JSI replaces the old bridge's asynchronous, batched JSON messages with direct calls into C++ host objects, which makes synchronous calls possible and removes the serialization step.
- Interviewers for React Native roles ask you to explain bridge vs JSI and to wire a TurboModule in Kotlin from a TypeScript spec, including the Codegen and package registration steps.
- Fabric changes how native views are created, laid out and mounted on Android; knowing the render, commit and mount phases helps you debug custom native components.
The simple explanation
- Old bridge: you write a letter, seal it in an envelope (JSON), drop it in an outbox that is emptied in batches, and wait for a reply letter.
- JSI: you walk to the next desk and hand over a typed form. You can wait for the answer on the spot, or ask to be called back later.
- TurboModules: the desk is only staffed the first time someone walks up, not at 9 a.m. every day (lazy load).
- Codegen: a clerk reads your spec once and prints the exact form both sides fill in, so nobody mistypes a field.
- Fabric: a new way to build and swap the whiteboard, prepared off to the side and then put up in one move.
The React Native New Architecture is the set of four pieces that replaced the old bridge: JSI, TurboModules, Fabric and Codegen. The old bridge serialized every JS-to-native call to JSON, queued it and delivered it asynchronously in batches, so native code could not return a value in the same call.
| Old | New | What changes for you |
|---|---|---|
| Bridge (async, batched JSON) | JSI (C++ API) | JS holds references to C++ host objects and calls them directly; no JSON |
| Native modules mostly set up at startup | TurboModules | A module is created the first time JS requests it (lazy) |
| Old renderer (UIManager over the bridge) | Fabric | C++ renderer: React renders, Yoga layout commits, the UI thread mounts views |
| Hand-written, untyped glue | Codegen | Reads your typed spec and generates the Android base class, iOS protocol and C++ bindings |
For an Android developer the practical shift is: you write a TypeScript spec file named Native<Something>.ts, add a codegenConfig block to package.json, and Codegen generates an abstract Java class (for example NativeHasherSpec) during the Gradle build. Your Kotlin module extends that class and is registered through a BaseReactPackage. JS gets it with TurboModuleRegistry.getEnforcing<Spec>('NativeHasher').
The spec's return types decide the threading. A method returning a plain value (string, number) is synchronous and runs on the JS thread. A method returning Promise<T> or void is asynchronous, so the JS thread does not wait for it.
Hermes is the default JS engine; in release builds it precompiles JavaScript to bytecode at build time. JSI is engine-agnostic, so the New Architecture does not require Hermes.
The main pitfall: a synchronous method that does slow work (network, disk, heavy hashing) blocks the JS thread. While it is blocked, React cannot process touches or state updates. Make such methods return a Promise instead.
Notes
- JSI is a C++ API that lets JavaScript hold references to C++ objects and call their methods. Your Kotlin module reaches it through Codegen-generated Java and JNI code; you do not write JNI by hand.
- TurboModules are lazy: the native instance is created the first time JS requests the module, not at app start.
ReactModuleInfohas aneedsEagerInitflag for the rare module that must start early. - Name the spec file with the
Nativeprefix (for examplespecs/NativeHasher.ts). Codegen finds it throughcodegenConfig(name,type,jsSrcsDir,android.javaPackageName) inpackage.json. - On Android, Codegen runs in the Gradle build (task
generateCodegenArtifactsFromSchema) and generates an abstract Java spec class that extendsReactContextBaseJavaModuleand implementsTurboModule. Your Kotlin class extends it. - Register the module with a
BaseReactPackage(getModuleplusgetReactModuleInfoProviderwithisTurboModule = true), then add the package togetPackages()inMainApplication. Library packages are autolinked into the generatedPackageList. - Synchronous spec methods (plain return types) run on the JS thread. Methods returning
Promise<T>orvoidare async; resolve or reject thecom.facebook.react.bridge.Promiseyou receive. TurboModuleRegistry.getEnforcingthrows if the module is missing;getreturnsnull. UsegetEnforcingfor modules the app cannot work without, so a missing registration fails loudly.- Legacy modules (a
ReactContextBaseJavaModulesubclass with@ReactMethodmethods) still load through the interop layer, but they skip Codegen's type checks. Write new modules as Turbo Native Modules. - Fabric keeps a shadow tree, but in C++: React renders on the JS thread, the commit phase runs Yoga layout, and the mount phase applies changes to Android views on the UI thread. Old Java
ReactShadowNodesubclasses do not work with Fabric. - Custom Fabric components on Android still use a
ViewManager, now with a Codegen-generated...ManagerInterfaceand...ManagerDelegatefrom a TypeScript component spec.
Code example
The TypeScript spec drives Codegen. It lives in specs/NativeHasher.ts:
import type { TurboModule } from 'react-native';
import { TurboModuleRegistry } from 'react-native';
export interface Spec extends TurboModule {
// Plain return type: synchronous, runs on the JS thread
shortHash(input: string): string;
// Promise return type: asynchronous, does not block the JS thread
sha256(input: string): Promise<string>;
}
export default TurboModuleRegistry.getEnforcing<Spec>('NativeHasher');With "codegenConfig": { "name": "NativeHasherSpec", "type": "modules", "jsSrcsDir": "specs", "android": { "javaPackageName": "com.example.hasher" } } in package.json, the Gradle build generates com.example.hasher.NativeHasherSpec. The Kotlin module and package:
package com.example.hasher
import com.facebook.react.BaseReactPackage
import com.facebook.react.bridge.NativeModule
import com.facebook.react.bridge.Promise
import com.facebook.react.bridge.ReactApplicationContext
import com.facebook.react.module.model.ReactModuleInfo
import com.facebook.react.module.model.ReactModuleInfoProvider
import java.security.MessageDigest
import java.util.concurrent.Executors
class NativeHasherModule(reactContext: ReactApplicationContext) :
NativeHasherSpec(reactContext) {
private val executor = Executors.newSingleThreadExecutor()
override fun getName() = NAME
// Synchronous: keep it tiny, the JS thread waits for the return value
override fun shortHash(input: String): String =
Integer.toHexString(input.hashCode())
// Asynchronous: do the real work off the JS thread and resolve later
override fun sha256(input: String, promise: Promise) {
executor.execute {
try {
val bytes = MessageDigest.getInstance("SHA-256")
.digest(input.toByteArray(Charsets.UTF_8))
promise.resolve(bytes.joinToString("") { "%02x".format(it) })
} catch (e: Exception) {
promise.reject("HASH_ERROR", e.message, e)
}
}
}
override fun invalidate() {
executor.shutdown()
super.invalidate()
}
companion object {
const val NAME = "NativeHasher"
}
}
class NativeHasherPackage : BaseReactPackage() {
override fun getModule(name: String, reactContext: ReactApplicationContext): NativeModule? =
if (name == NativeHasherModule.NAME) NativeHasherModule(reactContext) else null
override fun getReactModuleInfoProvider() = ReactModuleInfoProvider {
mapOf(
NativeHasherModule.NAME to ReactModuleInfo(
name = NativeHasherModule.NAME,
className = NativeHasherModule.NAME,
canOverrideExistingModule = false,
needsEagerInit = false,
isCxxModule = false,
isTurboModule = true
)
)
}
}NativeHasherSpecis generated from the.tsspec; you never write it. If you change the spec, the next build regenerates it and the Kotlin compiler flags any method you forgot to update.shortHashreturns a value directly, so JS gets it in the same call.sha256receives aPromisebecause the spec returnsPromise<string>; it resolves from a background executor.BaseReactPackage.getModuleis only called when JS first asks forNativeHasher, which is what makes the module lazy. AddNativeHasherPackage()to the list returned bygetPackages()inMainApplication.
Run the idea in plain Kotlin
interface HostModule {
fun call(method: String, arg: String): String
}
class GreeterModule : HostModule {
init { println("[native] GreeterModule constructed") }
override fun call(method: String, arg: String): String =
if (method == "greet") "Hello, " + arg else error("unknown method " + method)
}
// TurboModule-style registry: a module is built the first time JS asks for it
class LazyRegistry(private val factories: Map<String, () -> HostModule>) {
private val instances = mutableMapOf<String, HostModule>()
fun getEnforcing(name: String): HostModule =
instances.getOrPut(name) {
val factory = factories[name]
?: error("TurboModuleRegistry: '" + name + "' could not be found")
factory()
}
fun get(name: String): HostModule? =
if (name in factories) getEnforcing(name) else null
}
// Old-bridge style: calls become string messages, queued and delivered later in a batch
class OldBridge(private val module: HostModule) {
private val queue = mutableListOf<String>()
fun enqueue(method: String, arg: String) {
queue.add(method + ":" + arg)
}
fun flush(onResult: (String) -> Unit) {
for (message in queue) {
val method = message.substringBefore(":")
val arg = message.substringAfter(":")
onResult(module.call(method, arg))
}
queue.clear()
}
}
fun main() {
val registry = LazyRegistry(mapOf("Greeter" to { GreeterModule() }))
println("App started, no native module built yet")
val greeter = registry.getEnforcing("Greeter")
println("JSI sync result: " + greeter.call("greet", "Android"))
println("Same instance reused: " + (registry.getEnforcing("Greeter") === greeter))
val bridge = OldBridge(greeter)
bridge.enqueue("greet", "Kotlin")
println("Bridge call queued, no result yet")
bridge.flush { result -> println("Bridge async result: " + result) }
println("get on missing module: " + registry.get("Camera"))
try {
registry.getEnforcing("Camera")
} catch (e: IllegalStateException) {
println("getEnforcing threw: " + e.message)
}
}Expected output:
App started, no native module built yet
[native] GreeterModule constructed
JSI sync result: Hello, Android
Same instance reused: true
Bridge call queued, no result yet
Bridge async result: Hello, Kotlin
get on missing module: null
getEnforcing threw: TurboModuleRegistry: 'Camera' could not be found
In production
- After migrating a legacy module to a Turbo Native Module, users on slower Android devices reported that taps did nothing for a moment on the first screen.
- The new spec declared
loadConfig(): stringinstead ofloadConfig(): Promise<string>, so the method became synchronous. - The Kotlin implementation read and parsed a large file from disk, blocking the JS thread on every launch. The old module had been async, so the problem never showed up before.
- A Perfetto trace showed the JS thread busy inside the native call while the UI thread sat idle waiting for React updates.
- They changed the spec to return
Promise<string>, let Codegen regenerate the base class, and moved the file read onto a background executor that resolves thePromise. - The screen now renders a placeholder first and fills in when the
Promiseresolves. They added a review rule: synchronous spec methods must be cheap and do no I/O.
- A new feature worked on iOS but did nothing on Android.
- The JS code used
TurboModuleRegistry.get, which returnednullon Android, and every call was guarded with?., so nothing failed. - The module lived in the app, not in a library, so autolinking did not pick it up, and nobody had added its package to
getPackages()inMainApplication.
- They switched the spec to
TurboModuleRegistry.getEnforcing, which threw on the first Android launch with a clear "could not be found" error. - They added the package to
getPackages()afterPackageList(this).packages. - They added a smoke test that launches the app on an emulator in CI and calls each native module once, so a missing registration fails the build.
Common mistakes
- Doing I/O in a synchronous spec method. A plain return type makes the call synchronous on the JS thread, so slow work freezes touches and updates. Return a
Promiseand do the work on a background thread. - Using
TurboModuleRegistry.getfor a required module.getreturnsnullwhen the module is missing, so the app silently does nothing.getEnforcingthrows and points straight at the missing registration. - Writing new modules the legacy way. A
ReactContextBaseJavaModulewith@ReactMethodstill runs through the interop layer, but it has no Codegen spec, so a mismatch between JS and Kotlin shows up only at runtime. Write a spec and extend the generated class. - Forgetting to register an in-app package. Autolinking only covers libraries. A module inside your app must be added to
getPackages()inMainApplication, orgetEnforcingthrows at runtime. - Dropping the
Nativeprefix or thecodegenConfigblock. Without them Codegen does not generate the spec class, and the Kotlin build fails with an unresolved...Specreference. - Heavy work in the module constructor. The constructor runs on first access, often during a user interaction. Keep it cheap and start expensive setup lazily or on a background thread.
Interview questions
Answer out loud first. Then reveal the answer and compare it at each depth.
“What is the difference between the old React Native bridge and JSI?”
“What are TurboModules and how do they differ from legacy native modules?”
“What does Fabric change for an Android developer?”
“How does Codegen work and what does it produce on Android?”
Quiz
What is the primary advantage of JSI over the old React Native bridge?
When is a TurboModule's Kotlin instance created by default?
A spec declares readFile(path: string): string and the Kotlin implementation reads from disk. What happens?
Which call makes a missing TurboModule fail loudly instead of returning null?
0 of 4 answered
Mini task
Add a Turbo Native Module to a React Native app
- Create
specs/NativeGreeter.ts:import type { TurboModule } from 'react-native'; import { TurboModuleRegistry } from 'react-native'; export interface Spec extends TurboModule { greet(name: string): string; } export default TurboModuleRegistry.getEnforcing<Spec>('NativeGreeter'); - Add
"codegenConfig": { "name": "NativeGreeterSpec", "type": "modules", "jsSrcsDir": "specs", "android": { "javaPackageName": "com.example.greeter" } }topackage.json. - Run
cd android && ./gradlew generateCodegenArtifactsFromSchemaand find the generatedNativeGreeterSpecclass underandroid/app/build/generated/. - Create
NativeGreeterModule.ktthat extendsNativeGreeterSpec, overridesgetName()to return"NativeGreeter", and returns"Hello, " + namefromgreet. - Create
NativeGreeterPackage.ktextendingBaseReactPackage, following the example above, and addNativeGreeterPackage()togetPackages()inMainApplication.kt. - In a component, import the module and call
NativeGreeter.greet('Android')in auseEffect. Run the app withnpm run androidand check Metro's log. (In an Expo project the usual route is the Expo Modules API instead.) - Change
greetto returnPromise<string>in the spec, rebuild, and fix the Kotlin compile error by taking aPromiseparameter and callingpromise.resolve(...).
Done when: the app builds, getEnforcing finds the module at runtime, the greeting appears in the log, and you have seen the Kotlin compiler catch the spec change in step 7.