CodeBlanks Logo Icon CodeBlanks

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.

Practice 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 [].

Starter code

App.js
import React from 'react';
import * as Notifications from 'expo-notifications';

export function useNotification() {
  React.useEffect(() => {
    // set up the listener and return cleanup
  }, []);
}

Sample solution

App.js
const sub = Notifications.addNotificationReceivedListener((notification) => {
  console.log(notification.request.content.data);
});
return () => sub.remove();

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Write the listener function

Question
Notifications.addNotification____Listener((notification) => { console.log(notification); });
Answer
Notifications.addNotificationReceivedListener((notification) => { console.log(notification); });

Explanation: Received is called when a notification arrives.

2 Match each event to its role

Term Meaning
received When notification arrives
response When user taps
useEffect Setup place
sub.remove() Cleanup

3 When is the response listener called?

  • When the user taps the notification Correct answer
  • When the app is closed
  • When the notification first reaches the device
  • Only while the app opens

Explanation: The response listener fires when the user taps.

All lessons in Advanced