React Native
Native events
Learn native events and emitters.
Native events
A native event is a notification sent from the native side to JS. Example: when Bluetooth turns on, when headphones are plugged in, or when sensor data arrives, the native side emits an event. JS listens to these events with NativeEventEmitter.
Usage: first get an instance of the module new NativeEventEmitter(NativeModules.Bluetooth). Then listen to a specific event with addListener. When done, clean up with remove; this prevents memory leaks.
Listening with NativeEventEmitter
NativeEventEmitter is the class used to listen to native events. First an emitter is created with the module instance: const emitter = new NativeEventEmitter(NativeModules.Bluetooth). Then the event is listened with emitter.addListener('stateChanged', callback).
The callback receives the event payload. Important: the listener is removed when the component closes. Inside useEffect you write const sub = emitter.addListener(...) and clean up with return () => sub.remove(). This pattern prevents memory leaks.
Exercise Listen to a Bluetooth event
Complete the useBluetoothState hook. Import NativeEventEmitter from react-native. Create an emitter with new NativeEventEmitter(NativeModules.Bluetooth). Listen with addListener('stateChanged', handler); call sub.remove() in the useEffect return.
Show example solution
import { useEffect } from 'react';
import { NativeEventEmitter, NativeModules } from 'react-native';
export function useBluetoothState(handler) {
useEffect(() => {
const emitter = new NativeEventEmitter(NativeModules.Bluetooth);
const sub = emitter.addListener('stateChanged', handler);
return () => sub.remove();
}, []);
}
Test yourself
-
What does a native event report?
- State changes coming from the native side
- Only file names
- Only animations
- Only styles
Show answer
Only file names — A native event reports state changes coming from the native side.
-
Match the event parts
- NativeEventEmitter
- Event listener
- addListener
- Registers for an event
- 'stateChanged'
- Event name
- sub.remove()
- Cleans up
-
Write the event name
emitter.addListener('____', handler);
Show answer
emitter.addListener('stateChanged', handler);
Next lesson: TurboModules