Native modules and the New Architecture

Learn the React Native New Architecture (JSI, TurboModules, Fabric, Codegen) and write a Turbo Native Module for Android in Kotlin from a TypeScript spec. About 25 minutes.

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.

OldNewWhat 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 startupTurboModulesA module is created the first time JS requests it (lazy)
Old renderer (UIManager over the bridge)FabricC++ renderer: React renders, Yoga layout commits, the UI thread mounts views
Hand-written, untyped glueCodegenReads 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.

Old bridge versus JSI
Old bridge versus JSI Old architecture: JavaScript serializes a call to JSON, the bridge delivers it to the native module asynchronously in a batch, and the JSON reply comes back later. New architecture: JavaScript calls a C++ host object through JSI, which invokes the TurboModule directly and returns a value or a Promise, with no serialization step. Old architecture New architecture CALL AS JSON LATER, BATCHED JSON REPLY, ASYNC CALL HOST OBJECT DIRECT, NO JSON VALUE OR PROMISE JavaScript your RN code Old bridge async queue Native module Kotlin JSI C++ interface TurboModule Kotlin
The old bridge turns every call into JSON and delivers it later in a batch; JSI calls the TurboModule's C++ host object directly.

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. ReactModuleInfo has a needsEagerInit flag for the rare module that must start early.
  • Name the spec file with the Native prefix (for example specs/NativeHasher.ts). Codegen finds it through codegenConfig (name, type, jsSrcsDir, android.javaPackageName) in package.json.
  • On Android, Codegen runs in the Gradle build (task generateCodegenArtifactsFromSchema) and generates an abstract Java spec class that extends ReactContextBaseJavaModule and implements TurboModule. Your Kotlin class extends it.
  • Register the module with a BaseReactPackage (getModule plus getReactModuleInfoProvider with isTurboModule = true), then add the package to getPackages() in MainApplication. Library packages are autolinked into the generated PackageList.
  • Synchronous spec methods (plain return types) run on the JS thread. Methods returning Promise<T> or void are async; resolve or reject the com.facebook.react.bridge.Promise you receive.
  • TurboModuleRegistry.getEnforcing throws if the module is missing; get returns null. Use getEnforcing for modules the app cannot work without, so a missing registration fails loudly.
  • Legacy modules (a ReactContextBaseJavaModule subclass with @ReactMethod methods) 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 ReactShadowNode subclasses do not work with Fabric.
  • Custom Fabric components on Android still use a ViewManager, now with a Codegen-generated ...ManagerInterface and ...ManagerDelegate from 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
            )
        )
    }
}
  • NativeHasherSpec is generated from the .ts spec; 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.
  • shortHash returns a value directly, so JS gets it in the same call. sha256 receives a Promise because the spec returns Promise<string>; it resolves from a background executor.
  • BaseReactPackage.getModule is only called when JS first asks for NativeHasher, which is what makes the module lazy. Add NativeHasherPackage() to the list returned by getPackages() in MainApplication.

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

App freezes after migrating a storage module to a TurboModule
  • 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(): string instead of loadConfig(): 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.
The fix
  • 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 the Promise.
  • The screen now renders a placeholder first and fills in when the Promise resolves. They added a review rule: synchronous spec methods must be cheap and do no I/O.
Feature silently does nothing on Android
  • A new feature worked on iOS but did nothing on Android.
  • The JS code used TurboModuleRegistry.get, which returned null on 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() in MainApplication.
The fix
  • 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() after PackageList(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 Promise and do the work on a background thread.
  • Using TurboModuleRegistry.get for a required module. get returns null when the module is missing, so the app silently does nothing. getEnforcing throws and points straight at the missing registration.
  • Writing new modules the legacy way. A ReactContextBaseJavaModule with @ReactMethod still 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() in MainApplication, or getEnforcing throws at runtime.
  • Dropping the Native prefix or the codegenConfig block. Without them Codegen does not generate the spec class, and the Kotlin build fails with an unresolved ...Spec reference.
  • 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

  1. 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');
  2. Add "codegenConfig": { "name": "NativeGreeterSpec", "type": "modules", "jsSrcsDir": "specs", "android": { "javaPackageName": "com.example.greeter" } } to package.json.
  3. Run cd android && ./gradlew generateCodegenArtifactsFromSchema and find the generated NativeGreeterSpec class under android/app/build/generated/.
  4. Create NativeGreeterModule.kt that extends NativeGreeterSpec, overrides getName() to return "NativeGreeter", and returns "Hello, " + name from greet.
  5. Create NativeGreeterPackage.kt extending BaseReactPackage, following the example above, and add NativeGreeterPackage() to getPackages() in MainApplication.kt.
  6. In a component, import the module and call NativeGreeter.greet('Android') in a useEffect. Run the app with npm run android and check Metro's log. (In an Expo project the usual route is the Expo Modules API instead.)
  7. Change greet to return Promise<string> in the spec, rebuild, and fix the Kotlin compile error by taking a Promise parameter and calling promise.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.

Next: React Native performance