Native events
- React Native course
- Advanced
- Lesson 70/83
- 5 min
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.
Practice 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.
Starter code
import { useEffect } from 'react';
import { NativeModules } from 'react-native';
export function useBluetoothState(handler) {
useEffect(() => {
// create emitter and listen to 'stateChanged'
}, []);
}Sample 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();
}, []);
}Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What does a native event report?
- State changes coming from the native side
- Only file names Correct answer
- Only animations
- Only styles
Explanation: A native event reports state changes coming from the native side.
2 Match the event parts
| Term | Meaning |
|---|---|
NativeEventEmitter |
Event listener |
addListener |
Registers for an event |
'stateChanged' |
Event name |
sub.remove() |
Cleans up |
3 Write the event name
emitter.addListener('____', handler);
emitter.addListener('stateChanged', handler);
Explanation: stateChanged is the event name.