Writing Custom Native Code

Article · 2:00

A native module in Swift and Kotlin with the Expo Modules API, and when you actually need one.

First, check whether you need one. The ecosystem is large, and a module you write is a module you maintain through every React Native upgrade. You genuinely need native code when you are wrapping a vendor SDK with no React Native binding, when you need an API the framework has not exposed, or when a computation is too heavy for JavaScript and belongs in C++ or Swift.

The Expo Modules API is the pleasant way to write one. You declare the module in a small Swift or Kotlin DSL - name, functions, constants, events - and it generates the bridging code for both the old and new architectures. You do not write Objective-C headers, and you do not register anything by hand. npx create-expo-module@latest scaffolds the whole thing including a local-only variant for a module that lives inside one app rather than being published.

Three rules make the difference between a module that works and one that causes crashes nobody can reproduce. Anything touching the user interface must run on the main thread - DispatchQueue.main.async on iOS, the UI thread on Android. Long work must not block that thread. And every error must be converted into something JavaScript can catch, rather than throwing into a native stack that takes the app down.

Nitro Modules is the newer alternative, generating a thinner JSI binding for cases where even the Expo layer's overhead matters.

// ios/BrightnessModule.swift - the Expo Modules API, in Swift.
import ExpoModulesCore
import UIKit

public class BrightnessModule: Module {
  public func definition() -> ModuleDefinition {
    Name("Brightness")

    // Synchronous: reading a value the system already has.
    Function("getLevel") { () -> Double in
      return Double(UIScreen.main.brightness)
    }

    // Anything touching the UI must be on the main thread.
    AsyncFunction("setLevel") { (value: Double) in
      guard (0...1).contains(value) else {
        // Converted into an error JavaScript can catch, not a native throw.
        throw Exception(name: "ERR_RANGE", description: "Expected 0 to 1.")
      }
      DispatchQueue.main.async {
        UIScreen.main.brightness = CGFloat(value)
      }
    }

    Events("onBrightnessChange")
  }
}

// android/BrightnessModule.kt - the same module, in Kotlin.
//
// class BrightnessModule : Module() {
//   override fun definition() = ModuleDefinition {
//     Name("Brightness")
//     Function("getLevel") { currentBrightness() }
//     AsyncFunction("setLevel") { value: Double ->
//       require(value in 0.0..1.0) { "Expected 0 to 1." }
//       appContext.activityProvider?.currentActivity?.runOnUiThread {
//         applyBrightness(value)
//       }
//     }
//   }
// }

// Scaffold one, including a local-only module that lives in this app:
//   npx create-expo-module@latest --local