Summary - Native modules
- React Native course
- Advanced
- Lesson 72/83
- 5 min
Combine NativeMethods, events and TurboModules to write a native bridge.
Summary - Native modules
In this group you learned native modules, NativeMethods, platform-specific, native events and TurboModules. NativeModules carries all native modules; NativeModules.Battery.getLevel() calls a method. Platform.OS separates platforms.
NativeEventEmitter listens to native events; TurboModules provides fast calls via JSI in the new architecture. Now we will combine them into a simple native bridge skeleton.
Practice Summary - Battery level
Complete the getBattery function. Import NativeModules from react-native. Also import Platform.OS. If Platform.OS === 'android' call NativeModules.Battery.getLevel() and return it; else return null.
Starter code
import { NativeModules, Platform } from 'react-native';
export async function getBattery() {
// on Android read the level from Battery module; else return null
}Sample solution
import { NativeModules, Platform } from 'react-native';
export async function getBattery() {
if (Platform.OS === 'android') {
return await NativeModules.Battery.getLevel();
}
return null;
}Practice Summary - Event cleanup
Complete the useBluetooth hook. Create an emitter with NativeEventEmitter. Listen with addListener('stateChanged', handler). Call sub.remove() in the useEffect return.
Starter code
import { useEffect } from 'react';
import { NativeEventEmitter, NativeModules } from 'react-native';
export function useBluetooth(handler) {
useEffect(() => {
// create emitter and listen
}, []);
}Sample solution
import { useEffect } from 'react';
import { NativeEventEmitter, NativeModules } from 'react-native';
export function useBluetooth(handler) {
useEffect(() => {
const emitter = new NativeEventEmitter(NativeModules.Bluetooth);
const sub = emitter.addListener('stateChanged', handler);
return () => sub.remove();
}, []);
}Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Match the flow parts
| Term | Meaning |
|---|---|
NativeModules |
All modules |
Platform.OS |
Operating system |
NativeEventEmitter |
Listens to events |
TurboModules |
New architecture |
2 The EventEmitter class
const emitter = new ____(NativeModules.Bluetooth);
const emitter = new NativeEventEmitter(NativeModules.Bluetooth);
Explanation: NativeEventEmitter listens to native events.