Native Modules & Bridging
Kadang kamu butuh akses ke API native yang belum ada wrapper JavaScript-nya. Native Modules memungkinkan kamu menulis kode Swift/Kotlin dan memanggilnya dari JS.
Arsitektur Baru: Turbo Modules
// React Native New Architecture:
// Old Bridge: async, serialized JSON over bridge (lambat)
// JS ←→ [JSON Bridge] ←→ Native
// Turbo Modules: JSI (JavaScript Interface), synchronous, direct call
// JS ←→ [JSI - C++ layer] ←→ Native
// Hasilnya: 3-10x lebih cepat dari Old Bridge
Expo Modules API (Recommended)
# Buat native module dengan Expo Modules API
npx create-expo-module my-native-module
// modules/my-native-module/index.ts
import { NativeModulesProxy } from 'expo-modules-core';
export default NativeModulesProxy.MyNativeModule;
// modules/my-native-module/ios/MyNativeModule.swift
import ExpoModulesCore
public class MyNativeModule: Module {
public func definition() -> ModuleDefinition {
Name("MyNativeModule")
Function("getDeviceName") {
return UIDevice.current.name
}
AsyncFunction("heavyComputation") { (input: String) -> String in
// Proses berat di native thread
return processData(input)
}
}
}
// modules/my-native-module/android/MyNativeModule.kt
package expo.modules.mynativemodule
import expo.modules.kotlin.modules.Module
import expo.modules.kotlin.modules.ModuleDefinition
class MyNativeModule : Module() {
override fun definition() = ModuleDefinition {
Name("MyNativeModule")
Function("getDeviceName") {
android.os.Build.MODEL
}
}
}
Panggil dari JavaScript
import MyNativeModule from './modules/my-native-module';
// Synchronous
const deviceName = MyNativeModule.getDeviceName();
console.log('Device:', deviceName);
// Async
const result = await MyNativeModule.heavyComputation('input data');
console.log('Result:', result);
Kapan Butuh Native Module?
- Hardware spesifik — Bluetooth LE, NFC, custom sensor
- Performa kritis — Image processing, crypto, ML inference
- SDK pihak ketiga — Payment SDK (GoPay, OVO), analytics native
- Platform API baru — Fitur OS terbaru yang belum ada di Expo/RN
Fabric & New Architecture
// React Native New Architecture terdiri dari:
// 1. Turbo Modules — Native modules baru (JSI-based)
// 2. Fabric — Rendering engine baru (concurrent)
// 3. Codegen — Auto-generate native code dari TypeScript specs
// Aktifkan di app.json (Expo SDK 51+):
{
"expo": {
"newArchEnabled": true
}
}
Tips
- Cek Expo SDK dulu — Sebelum buat native module, cari apakah sudah ada di expo packages
- Community packages — react-native-community dan expo punya banyak wrapper siap pakai
- Config Plugin — Untuk modify native config tanpa eject, gunakan Expo Config Plugins