# Event listeners (/en/realtime-media/rtm/build/send-and-receive-messages/add-event-listener/react-native)

> For AI agents: see the complete documentation index at [llms.txt](/llms.txt).

To receive message and event notifications when you subscribe to or join channels, you add an event listener. An event listener is triggered by the SDK to inform the client about Signaling events and state changes. The listener enables you to respond to events like successful connection to Signaling, token expiration, received messages, and other presence, storage, and lock events.

## Prerequisites

Ensure that you have integrated the Signaling SDK in your project and implemented the framework functionality from the [SDK quickstart](../../index) page.

## Implement event listeners

This section shows how to use the Signaling SDK to implement event listeners.

### Add an event listener

Signaling provides the `useRtmEvent` hook to process messages and event notifications. Each message and event notification has a corresponding event handler, where you implement your own processing logic. Refer to the following code to implement listeners in your app:

```tsx
// Listen to messages received via Signaling channel
useRtmEvent(engine, 'message', (evt) => {
 const msg = new MessageEvent(evt);
 console.log('[You] received a message:', msg.message, 'from:', msg.publisher);
});

// Listen to Signaling link state changes
useRtmEvent(engine, 'linkState', (eventData) => {
 console.log('Link state changed:', eventData.currentState, 'reason:', eventData.reason);

 if (eventData.currentState === RtmLinkState.connected) {
   console.log('✅ Connected to Signaling');
 } else if (eventData.currentState === RtmLinkState.failed) {
   console.log('❌ Connection failed:', eventData.reason);
 }
});

// Listen to presence events such as user join, leave, or state change
useRtmEvent(engine, 'presence', (presenceData) => {
 console.log('[Signaling] Presence event:', presenceData.eventType);
 console.log('User:', presenceData.publisher, 'Channel:', presenceData.channelName);
});

// Listen to topic-related events such as topic creation, update, or deletion
useRtmEvent(engine, 'topic', (topicEvent) => {
 console.log('[Signaling] Topic event:', topicEvent.eventType);
 console.log('Topic:', topicEvent.topicName, 'Publisher:', topicEvent.publisher);
});

// Listen to updates in shared storage
useRtmEvent(engine, 'storage', (storageData) => {
 console.log('[Signaling] Storage event:', storageData.eventType);
 console.log('Storage type:', storageData.storageType, 'Channel:', storageData.channelName);
});

// Listen to channel lock or unlock events
useRtmEvent(engine, 'lock', (eventData) => {
 console.log('[Signaling] Lock event:', eventData.eventType);
 console.log('Lock:', eventData.lockName, 'Channel:', eventData.channelName);
});

// Listen to token expiration warnings
useRtmEvent(engine, 'tokenPrivilegeWillExpire', (channelName) => {
 console.log('[Signaling] Token privilege will expire for channel:', channelName);
 // Generate and renew token here
});
```

### Event listener lifecycle

The `useRtmEvent` hook provides automatic lifecycle management:

* **Automatic registration**: Listeners are added when the component mounts
* **Automatic cleanup**: Listeners are removed when the component unmounts
* **Dependency tracking**: Hook re-registers listeners when dependencies change
* **Memory leak prevention**: No manual cleanup required

```tsx
// Event listeners are automatically managed by the hook
useEffect(() => {
 // useRtmEvent hooks automatically register listeners when component mounts
 console.log('Component mounted - event listeners active');

 return () => {
   // Listeners are automatically removed when component unmounts
   console.log('Component unmounting - listeners automatically cleaned up');
 };
}, []);
```

<CalloutContainer type="info">
  <CalloutDescription>
    The `useRtmEvent` hook is the recommended approach for React Native applications as it follows React best practices and prevents common memory leak issues.
  </CalloutDescription>
</CalloutContainer>

### Signaling events

Signaling SDK offers the following events:

| Event Listener             | Description                                                                                                                                                                                                                                   | Common Use Cases                                                 |
| -------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------- |
| `message`                  | Receive message notifications from all message channels you have subscribed to, or topic message notifications from stream channels you have joined. Includes channel name, channel type, topic name, sender, message content, and timestamp. | Chat applications, real-time notifications, data synchronization |
| `linkState`                | Receive event notifications for client network connection status changes. Includes current state, previous state, reason for change, and error codes.                                                                                         | Connection monitoring, retry logic, user status indicators       |
| `presence`                 | Receive online status event notifications from remote users in subscribed message channels and joined stream channels. Includes user join/leave events, state changes, and user metadata.                                                     | User presence indicators, active user lists, status updates      |
| `topic`                    | Receive notifications of topic change events in stream channels you have joined. Includes topic creation, updates, user join/leave topic events.                                                                                              | Stream channel management, topic subscription handling           |
| `storage`                  | Receive channel metadata and user metadata event notifications. Includes metadata updates, deletions, and synchronization events.                                                                                                             | Data persistence, shared state management, user profiles         |
| `lock`                     | Receive lock event notifications for distributed resource management. Includes lock acquisition, release, and expiration events.                                                                                                              | Resource coordination, mutual exclusion, distributed locks       |
| `tokenPrivilegeWillExpire` | Receive event notifications when the client token is about to expire (30 seconds before expiration).                                                                                                                                          | Token refresh, authentication management, session handling       |

For details on the parameters passed in by each event, refer the [API reference](https://api-ref.agora.io/en/signaling-sdk/react-native/2.x#add-listener-1).

    
  
      
  
      
  
      
  
