React Native
Notification events
Learn notification taps and events.
Notification events
When a notification arrives or the user taps it, your app receives an event. Notifications.addNotificationReceivedListener is called when a notification arrives while the app is open. Notifications.addNotificationResponseReceivedListener is called when the user taps the notification.
These listeners are set up inside useEffect and removed when the component unmounts. Each listener takes a function; this function receives the notification or response object as its parameter. The notification.request.content.data property of the response object carries the free data attached to the notification.
useEffect and cleanup
You set up listeners inside useEffect. This hook is called once when the component mounts. You add listeners inside it and return a cleanup function. The cleanup function removes the listeners when the component unmounts; this prevents responding to the same notification twice.
Example pattern: useEffect(() => {{ const sub = Notifications.addNotificationReceivedListener(handle); return () => sub.remove(); }}, []). The empty dependency array [] ensures the hook is called only once. sub.remove() cleans up the listener.
Exercise Set up the listeners
Complete the empty useEffect. Set up a listener with Notifications.addNotificationReceivedListener; the function should console.log the notification.request.content.data. Assign the listener to const sub = .... Clean it up with return () => sub.remove();. Use an empty dependency array [].
Show example solution
const sub = Notifications.addNotificationReceivedListener((notification) => {
console.log(notification.request.content.data);
});
return () => sub.remove();
Test yourself
-
Write the listener function
Notifications.addNotification____Listener((notification) => { console.log(notification); });
Show answer
Notifications.addNotificationReceivedListener((notification) => { console.log(notification); });
-
Match each event to its role
- received
- When notification arrives
- response
- When user taps
- useEffect
- Setup place
- sub.remove()
- Cleanup
-
When is the response listener called?
- When the user taps the notification
- When the app is closed
- When the notification first reaches the device
- Only while the app opens
Show answer
When the user taps the notification — The response listener fires when the user taps.
Next lesson: Summary - Push notifications