Bird
Raised Fist0
React Nativemobile~10 mins

Push notifications (expo-notifications) in React Native

Choose your learning style10 modes available
Introduction

Push notifications let your app send messages to users even when they are not using the app. This helps keep users informed and engaged.

To remind users about an upcoming event or appointment.
To alert users about new messages or updates.
To send promotional offers or news.
To notify users about important app changes or alerts.
Syntax
React Native
import * as Notifications from 'expo-notifications';

// Request permission
const permission = await Notifications.requestPermissionsAsync();

// Get device push token
const token = await Notifications.getExpoPushTokenAsync();

// Listen for notifications
Notifications.addNotificationReceivedListener(notification => {
  console.log(notification);
});

Always ask user permission before sending notifications.

The push token uniquely identifies the device for sending notifications.

Examples
This asks the user to allow notifications.
React Native
const permission = await Notifications.requestPermissionsAsync();
This gets the device token needed to send push notifications.
React Native
const token = await Notifications.getExpoPushTokenAsync();
This listens for notifications received while the app is open.
React Native
Notifications.addNotificationReceivedListener(notification => {
  console.log(notification);
});
Sample App

This app asks permission for notifications, gets the device token, and shows it on screen. When you press the button, it sends a test notification to your device. Notifications received while the app is open show their title and body below the button.

React Native
import React, { useEffect, useState } from 'react';
import { View, Text, Button, Platform } from 'react-native';
import * as Notifications from 'expo-notifications';
import * as Device from 'expo-device';

export default function App() {
  const [expoPushToken, setExpoPushToken] = useState('');
  const [notification, setNotification] = useState(false);

  useEffect(() => {
    registerForPushNotificationsAsync().then(token => setExpoPushToken(token));

    const subscription = Notifications.addNotificationReceivedListener(notification => {
      setNotification(notification);
    });

    return () => subscription.remove();
  }, []);

  return (
    <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
      <Text>Your Expo Push Token:</Text>
      <Text selectable>{expoPushToken}</Text>
      <View style={{ marginTop: 20 }}>
        <Button
          title="Press to Send Test Notification"
          onPress={async () => {
            await sendPushNotification(expoPushToken);
          }}
        />
      </View>
      {notification ? (
        <View style={{ marginTop: 20 }}>
          <Text>Last Notification:</Text>
          <Text>{notification.request.content.title}</Text>
          <Text>{notification.request.content.body}</Text>
        </View>
      ) : null}
    </View>
  );
}

async function sendPushNotification(expoPushToken) {
  const message = {
    to: expoPushToken,
    sound: 'default',
    title: 'Test Notification',
    body: 'This is a test push notification',
    data: { someData: 'goes here' },
  };

  await fetch('https://exp.host/--/api/v2/push/send', {
    method: 'POST',
    headers: {
      Accept: 'application/json',
      'Accept-Encoding': 'gzip, deflate',
      'Content-Type': 'application/json'
    },
    body: JSON.stringify(message)
  });
}

async function registerForPushNotificationsAsync() {
  let token;
  if (Device.isDevice) {
    const { status: existingStatus } = await Notifications.getPermissionsAsync();
    let finalStatus = existingStatus;
    if (existingStatus !== 'granted') {
      const { status } = await Notifications.requestPermissionsAsync();
      finalStatus = status;
    }
    if (finalStatus !== 'granted') {
      alert('Failed to get push token for push notification!');
      return;
    }
    token = (await Notifications.getExpoPushTokenAsync()).data;
  } else {
    alert('Must use physical device for Push Notifications');
  }

  if (Platform.OS === 'android') {
    Notifications.setNotificationChannelAsync('default', {
      name: 'default',
      importance: Notifications.AndroidImportance.MAX,
      vibrationPattern: [0, 250, 250, 250],
      lightColor: '#FF231F7C',
    });
  }

  return token;
}
OutputSuccess
Important Notes

Push notifications require a physical device; they do not work on simulators or emulators.

Always handle user permission carefully and explain why notifications are useful.

Use notification channels on Android for better control of notification behavior.

Summary

Push notifications keep users informed even when the app is closed.

Use expo-notifications to request permission, get tokens, and listen for notifications.

Test notifications by sending messages to the device token from your app or server.

Practice

(1/5)
1. What is the main purpose of using expo-notifications in a React Native app?
easy
A. To create animations for app screens
B. To send and receive push notifications to keep users informed
C. To manage app navigation between screens
D. To handle user authentication and login

Solution

  1. Step 1: Understand the role of expo-notifications

    The expo-notifications library is designed to handle push notifications in React Native apps.
  2. Step 2: Identify the correct purpose

    It allows apps to send and receive notifications, keeping users informed even when the app is closed.
  3. Final Answer:

    To send and receive push notifications to keep users informed -> Option B
  4. Quick Check:

    expo-notifications = Push notifications [OK]
Hint: Remember: expo-notifications is for alerts, not UI or auth [OK]
Common Mistakes:
  • Confusing notifications with navigation or animations
  • Thinking expo-notifications manages user login
  • Assuming it handles UI styling
2. Which of the following is the correct way to request notification permissions using expo-notifications?
easy
A. await Notifications.requestPermissionsAsync();
B. Notifications.getPermissions();
C. await Notifications.askForPermissions();
D. Notifications.permissionRequest();

Solution

  1. Step 1: Recall the correct method name

    The official method to request permissions is requestPermissionsAsync() from expo-notifications.
  2. Step 2: Check syntax correctness

    The method is asynchronous and should be awaited: await Notifications.requestPermissionsAsync();
  3. Final Answer:

    await Notifications.requestPermissionsAsync(); -> Option A
  4. Quick Check:

    Permission request method = requestPermissionsAsync [OK]
Hint: Look for async method starting with 'request' [OK]
Common Mistakes:
  • Using non-existent methods like getPermissions or askForPermissions
  • Forgetting to await the async call
  • Using incorrect method names
3. Given the code snippet below, what will be logged when a notification is received?
import * as Notifications from 'expo-notifications';

Notifications.addNotificationReceivedListener(notification => {
  console.log(notification.request.content.title);
});

// Assume a notification with title 'Hello User' arrives
medium
A. undefined
B. notification
C. Hello User
D. Error: notification is not defined

Solution

  1. Step 1: Understand the listener callback

    The listener receives a notification object, and logs notification.request.content.title.
  2. Step 2: Match the notification content

    The notification has a title 'Hello User', so that string will be logged.
  3. Final Answer:

    Hello User -> Option C
  4. Quick Check:

    Logged title = 'Hello User' [OK]
Hint: Listener logs notification title property [OK]
Common Mistakes:
  • Expecting the whole notification object to be logged
  • Confusing property names or missing nested fields
  • Assuming undefined if not familiar with notification structure
4. What is wrong with this code snippet for getting the push token?
import * as Notifications from 'expo-notifications';

const getToken = async () => {
  const token = Notifications.getExpoPushTokenAsync();
  console.log(token);
};

getToken();
medium
A. Missing await before Notifications.getExpoPushTokenAsync()
B. Wrong import statement for Notifications
C. console.log should be inside a .then() block
D. getToken function should not be async

Solution

  1. Step 1: Identify async function usage

    The method getExpoPushTokenAsync() returns a Promise and must be awaited.
  2. Step 2: Check the code for await

    The code calls Notifications.getExpoPushTokenAsync() without await, so token is a Promise, not the actual token.
  3. Final Answer:

    Missing await before Notifications.getExpoPushTokenAsync() -> Option A
  4. Quick Check:

    Async calls need await to get result [OK]
Hint: Always await async calls to get actual values [OK]
Common Mistakes:
  • Forgetting to await async functions
  • Misunderstanding Promises vs values
  • Incorrect import statements
  • Logging before Promise resolves
5. You want to send a push notification only when the user has granted permission. Which sequence of steps correctly implements this using expo-notifications?
hard
A. Send notification directly without requesting permission or token
B. Get token first with getExpoPushTokenAsync(), then request permission with requestPermissionsAsync()
C. Only request permission and send notification without getting token
D. Request permission with requestPermissionsAsync(), check status, then get token with getExpoPushTokenAsync() if granted

Solution

  1. Step 1: Request notification permission

    Use requestPermissionsAsync() to ask the user for permission and check the returned status.
  2. Step 2: Get push token if permission granted

    If permission is granted, call getExpoPushTokenAsync() to get the device token for sending notifications.
  3. Step 3: Send notification using the token

    Use the token to send push notifications from your server or app.
  4. Final Answer:

    Request permission with requestPermissionsAsync(), check status, then get token with getExpoPushTokenAsync() if granted -> Option D
  5. Quick Check:

    Permission first, then token, then send [OK]
Hint: Always request permission before getting token [OK]
Common Mistakes:
  • Getting token before permission
  • Sending notifications without token
  • Skipping permission check
  • Assuming permission is granted by default
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard