Skip to content

Nitro: a framework for fast native modules in React Native

updated

Nitro is described in its documentation as a framework for building powerful and fast native modules in React Native.

Core concepts

  • A Nitro Module is a library built with Nitro and contains one or more Hybrid Objects.
  • A Hybrid Object is a native object implemented in C++, Swift or Kotlin.
  • Nitrogen is a code generator that library authors can use to produce native bindings from a custom TypeScript interface.

A spec is declared in TypeScript, for example in Math.nitro.ts:

interface Math extends HybridObject {
  readonly pi: number
  add(a: number, b: number): number
}

It is then implemented natively, such as a Swift HybridMath class conforming to HybridMathSpec, and accessed from JS:

const math = NitroModules.createHybridObject<Math>('Math')
const result = math.add(5, 7)

Performance

The docs include a benchmark measuring total execution time for calling a single native method 100.000 times. For addNumbers(...), ExpoModules took 434.85ms, TurboModules 115.86ms and NitroModules 7.27ms. For addStrings(...), the figures were 429.53ms, 179.02ms and 29.94ms. The documentation notes that these benchmarks cover extreme cases and do not necessarily reflect real-world use; full context is in NitroBenchmarks.

Nitro is built on top of JSI with a lightweight layer, and much of its type-checking happens at compile time using C++ templates or constexpr. It does not use Objective-C; instead it relies on the new Swift <> C++ interop. Hybrid Objects are built on jsi::NativeState rather than jsi::HostObject, giving them native prototypes and a known native memory size so the garbage collector can clean up unused objects.

Type and null safety

With nitrogen, TypeScript specs serve as the single source of truth, and generated native interfaces must match the declared types exactly. A function declared with a number must be implemented as a Double on the native side, or the app will not compile. According to the docs, a Nitro Module cannot return a type that TypeScript does not expect, which also guarantees null-safety.

Object-oriented approach

Every Hybrid Object is a native object that can be created, passed around and destroyed, for example an ImageEditor that returns Image objects. Functions or callbacks are first-class citizens that can be kept in memory, called repeatedly and cleaned up automatically, somewhat like how Turbo-Modules implement events.

Swift and Kotlin

For Swift, Nitro bridges directly from C++. Generated specs are Swift protocols, properties map to Swift properties, and async functions can use async/await through the Promise.async API.

For Kotlin, Nitro bridges directly using fbjni, without requiring Java classes. Generated specs are Kotlin interfaces, properties map to Kotlin properties, and async functions can use coroutines via Promise.async.

Source: web.archive.org