Skip to content
Tutorials Center
My learning

Topics

Lesson 46 of 71 ยท Native Features

Native Modules, Expo Modules and Config Plugins

Know when JavaScript is not enough in React Native: Turbo Modules, the Expo Modules API, config plugins, prebuild and custom development clients explained.

Most React Native apps never need to write a line of Swift or Kotlin. Expo and the community already wrap the camera, storage, notifications and hundreds of other features. But sooner or later you meet a feature nobody has wrapped yet: a vendor's payment SDK, a Bluetooth gadget, an iOS widget, or a calculation that must run at native speed. Then you need to cross the line between JavaScript and the platform.

This lesson is a map of that border. You will learn when JavaScript is not enough, how a native module is shaped, what Turbo Modules and the Expo Modules API are, how config plugins edit native project files for you, what prebuild does, and why a custom development client replaces Expo Go once you add native code.

Read-only and stand-in. Native modules are Swift, Kotlin and C++ compiled into an app, which cannot happen in a browser. The real code is shown in plain blocks. The TryIts run stand-ins: a module registry that mimics the JavaScript side of a call, and a config plugin pipeline that edits plain objects. They teach the shape of the system, not the compilers.

When JavaScript is not enough

Your JavaScript runs inside the Hermes engine (see How React Native Runs Your Code). It can reach the phone only through native code that someone exposed. You need new native code when:

  • A platform API has no library yet, for example a new iOS framework or an Android system service.
  • You must integrate a vendor SDK that ships only as native code (payments, maps, analytics, hardware).
  • A task is performance critical: image or audio processing, cryptography, large data parsing.
  • You need deep platform features such as home-screen widgets, app extensions or background services.

Before writing native code, check three cheaper options. Is there already an Expo or community package? Can the web or a plain fetch solve it? Can a small piece of JavaScript do the job fast enough? Native code doubles your maintenance: two languages, two toolchains, and a separate test setup for each platform.

What a native module is

A native module is a class on the native side whose methods are callable from JavaScript, plus a thin JavaScript wrapper that gives those methods types and friendly names. Three kinds of things cross the border:

  • Functions you call (synchronously or returning a promise).
  • Events the native side sends to JavaScript (a sensor reading, a download progress).
  • Views, native UI components that you place in your tree like any other component.

Arguments and return values must be simple data: numbers, strings, booleans, arrays, plain objects, and null. You cannot pass a JavaScript function that runs on a native thread, or a class instance. Calls are asynchronous by default, because blocking the JavaScript thread while native code works would freeze the app.

What crosses the border

Functions Call native code, get a value or a promise.
Events Native pushes data to JavaScript.
Views Native UI used as a component.

Only plain data crosses: numbers, strings, arrays, objects.

1 / 2

Turbo Modules: the New Architecture way

Turbo Modules are React Native's native module system in the New Architecture. Instead of sending JSON messages over an asynchronous bridge, JavaScript holds a direct reference to the native object through JSI (the JavaScript Interface), so a call can even be synchronous when that makes sense. Modules also load lazily: a Turbo Module is created the first time JavaScript asks for it, which helps startup time.

You describe the module's shape in a typed spec file, and a tool called Codegen reads the spec and generates the native interfaces you then implement:

TypeScript
// NativeDeviceInfo.ts
import type { TurboModule } from 'react-native';
import { TurboModuleRegistry } from 'react-native';

export interface Spec extends TurboModule {
  getBatteryPercent(): number;
  getDeviceName(): Promise<string>;
}

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

The spec is the contract. If the native side does not match it, Codegen fails the build instead of letting a mismatch crash a user's phone. You then write the Objective-C++/Swift and Java/Kotlin implementations against the generated interfaces. That is powerful, but there is a good amount of setup, so most app developers reach for the Expo Modules API first.

The Expo Modules API

The Expo Modules API lets you write a module in Swift and Kotlin using a short, declarative DSL. The same API builds all of Expo's own packages. You start from a template:

Terminal
npx create-expo-module@latest my-device-info --local

The Swift side declares a name and the functions:

Swift
import ExpoModulesCore
import UIKit

public class DeviceInfoModule: Module {
  public func definition() -> ModuleDefinition {
    Name("DeviceInfo")

    Function("getBatteryPercent") { () -> Int in
      UIDevice.current.isBatteryMonitoringEnabled = true
      return Int(UIDevice.current.batteryLevel * 100)
    }

    AsyncFunction("getDeviceName") { () -> String in
      return UIDevice.current.name
    }
  }
}

and the Kotlin side mirrors it:

Kotlin
package expo.modules.deviceinfo

import android.content.Context
import android.os.BatteryManager
import expo.modules.kotlin.modules.Module
import expo.modules.kotlin.modules.ModuleDefinition

class DeviceInfoModule : Module() {
  override fun definition() = ModuleDefinition {
    Name("DeviceInfo")

    Function("getBatteryPercent") {
      val context = appContext.reactContext ?: return@Function -1
      val manager = context.getSystemService(Context.BATTERY_SERVICE) as BatteryManager
      manager.getIntProperty(BatteryManager.BATTERY_PROPERTY_CAPACITY)
    }
  }
}

In JavaScript you load it by name:

TypeScript
import { requireNativeModule } from 'expo';

const DeviceInfo = requireNativeModule('DeviceInfo');

export function batteryPercent(): number {
  return DeviceInfo.getBatteryPercent();
}

The DSL also has Events("onChange") for events and a View block for native components. Two things to notice: you write both platforms separately (the DSL is shared, the platform APIs are not), and the JavaScript name matches the Name(...) string exactly.

Config plugins

Native projects are full of settings: an iOS Info.plist, an Android manifest, Gradle files, entitlements. Editing them by hand is fragile. A config plugin is a small JavaScript function that receives your app config and returns a changed one, using helpers called mods that edit specific native files.

JavaScript
// plugins/withCameraPermission.js
const { withInfoPlist, withAndroidManifest } = require('expo/config-plugins');

module.exports = function withCameraPermission(config, { reason }) {
  config = withInfoPlist(config, (c) => {
    c.modResults.NSCameraUsageDescription = reason;
    return c;
  });

  config = withAndroidManifest(config, (c) => {
    const manifest = c.modResults.manifest;
    manifest['uses-permission'] = manifest['uses-permission'] ?? [];
    manifest['uses-permission'].push({
      $: { 'android:name': 'android.permission.CAMERA' },
    });
    return c;
  });

  return config;
};

You enable it in the app config, with options:

JSON
{
  "expo": {
    "plugins": [["./plugins/withCameraPermission", { "reason": "Scan receipts." }]]
  }
}

Libraries ship their own plugins, which is why ["expo-camera", { "cameraPermission": "..." }] works in Camera, Location and Sensors. Plugins run in order, and each one gets the result of the previous one.

Prebuild: native projects on demand

An Expo project has no ios/ and android/ folders by default. The command npx expo prebuild generates them from your app config, your installed packages and your config plugins. This idea is called Continuous Native Generation (CNG): the native folders are an output, not hand-maintained source, so upgrading Expo is a matter of updating versions and running prebuild again.

Terminal
npx expo prebuild          # generate ios/ and android/
npx expo prebuild --clean  # delete them and regenerate from scratch

Because the folders are generated, put changes that must survive in config plugins, not in the generated files. Many teams add ios/ and android/ to .gitignore for exactly this reason. If you do edit native files directly, you have chosen to maintain them yourself (sometimes called a bare workflow), and a later --clean would erase your edits.

Development builds replace Expo Go

Expo Go is a ready-made app with a fixed set of native modules inside. That is why it works with no build step, and also why it cannot run your own module or a library with native code it does not contain. Once you add one, you build a custom development client: your own app, built with expo-dev-client, that behaves like Expo Go but contains exactly your native code.

Terminal
npx expo install expo-dev-client
npx expo run:ios        # build locally and install on a simulator or device
npx expo run:android
eas build --profile development --platform all   # or build in the cloud

You rebuild the client only when native code or a plugin changes. Everyday JavaScript edits still reload instantly through Fast Refresh. See Builds with EAS and App Store Submission for build profiles.

Stand-in: a module registry

This stand-in models the JavaScript side of a module call: a registry keyed by name, a lookup that fails loudly when the module is missing, and calls that are either synchronous or asynchronous. It also checks that arguments are plain data, as the real border does.

A fake native module registry

The missing-module error is the one you will meet in real life: it appears when your JavaScript imports a package whose native half is not inside the app you are running, which is the classic symptom of using Expo Go (or an old dev client) with a new native dependency. The cure is to rebuild the client.

Stand-in: a config plugin pipeline

Config plugins are plain functions applied in order. The stand-in below runs three of them over a small object that plays the role of the generated native settings.

Config plugins applied in order

The final object holds every setting: each plugin added its own keys without knowing about the others. That is the real value of plugins: native configuration becomes small, reusable, testable functions instead of hand-edited XML.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which situation most clearly requires writing native code?

    JavaScript can reach the platform only through native code someone exposed. A native-only SDK needs a module around it. The other tasks are plain JavaScript.
  2. 2. What does a config plugin do?

    A config plugin is a function that receives the app config and returns a modified one, using mods that edit native files during prebuild.
  3. 3. Why does your app crash with a missing native module error in Expo Go after you install a library with native code?

    Expo Go cannot contain native code it was not built with. A custom development client includes your libraries' native halves.
  4. 4. What is true about the ios and android folders in a project that uses Continuous Native Generation?

    With CNG the native folders are generated, so lasting changes belong in config plugins. A clean prebuild recreates them from scratch.
  5. 5. Which values can cross the JavaScript-native border?

    The border carries plain serializable data. Functions and class instances do not cross as live objects.

Summary

  • Write native code only when no package exists, a vendor SDK demands it, or performance requires it. It doubles your maintenance.
  • A native module exposes functions, events and views; only plain data crosses the border.
  • Turbo Modules use a typed spec and Codegen in the New Architecture; the Expo Modules API offers a Swift and Kotlin DSL for the same job.
  • Config plugins edit native settings from JavaScript, and npx expo prebuild generates the native folders on demand.
  • Expo Go has a fixed set of native modules; a custom development client carries your own.
  • Rebuild the client after native changes; everything else stays on fast JavaScript reload.

Next, make your interface move in Animations with the Animated API.