Push notifications let your app send messages to users even when they are not using the app. This helps keep users informed and engaged.
Push notifications (expo-notifications) in 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.
const permission = await Notifications.requestPermissionsAsync();const token = await Notifications.getExpoPushTokenAsync();Notifications.addNotificationReceivedListener(notification => {
console.log(notification);
});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.
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; }
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.
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
expo-notifications in a React Native app?Solution
Step 1: Understand the role of expo-notifications
Theexpo-notificationslibrary is designed to handle push notifications in React Native apps.Step 2: Identify the correct purpose
It allows apps to send and receive notifications, keeping users informed even when the app is closed.Final Answer:
To send and receive push notifications to keep users informed -> Option BQuick Check:
expo-notifications = Push notifications [OK]
- Confusing notifications with navigation or animations
- Thinking expo-notifications manages user login
- Assuming it handles UI styling
Solution
Step 1: Recall the correct method name
The official method to request permissions isrequestPermissionsAsync()from expo-notifications.Step 2: Check syntax correctness
The method is asynchronous and should be awaited:await Notifications.requestPermissionsAsync();Final Answer:
await Notifications.requestPermissionsAsync(); -> Option AQuick Check:
Permission request method = requestPermissionsAsync [OK]
- Using non-existent methods like getPermissions or askForPermissions
- Forgetting to await the async call
- Using incorrect method names
import * as Notifications from 'expo-notifications';
Notifications.addNotificationReceivedListener(notification => {
console.log(notification.request.content.title);
});
// Assume a notification with title 'Hello User' arrivesSolution
Step 1: Understand the listener callback
The listener receives a notification object, and logsnotification.request.content.title.Step 2: Match the notification content
The notification has a title 'Hello User', so that string will be logged.Final Answer:
Hello User -> Option CQuick Check:
Logged title = 'Hello User' [OK]
- Expecting the whole notification object to be logged
- Confusing property names or missing nested fields
- Assuming undefined if not familiar with notification structure
import * as Notifications from 'expo-notifications';
const getToken = async () => {
const token = Notifications.getExpoPushTokenAsync();
console.log(token);
};
getToken();Solution
Step 1: Identify async function usage
The methodgetExpoPushTokenAsync()returns a Promise and must be awaited.Step 2: Check the code for await
The code callsNotifications.getExpoPushTokenAsync()withoutawait, sotokenis a Promise, not the actual token.Final Answer:
Missing await before Notifications.getExpoPushTokenAsync() -> Option AQuick Check:
Async calls need await to get result [OK]
- Forgetting to await async functions
- Misunderstanding Promises vs values
- Incorrect import statements
- Logging before Promise resolves
Solution
Step 1: Request notification permission
UserequestPermissionsAsync()to ask the user for permission and check the returned status.Step 2: Get push token if permission granted
If permission is granted, callgetExpoPushTokenAsync()to get the device token for sending notifications.Step 3: Send notification using the token
Use the token to send push notifications from your server or app.Final Answer:
Request permission with requestPermissionsAsync(), check status, then get token with getExpoPushTokenAsync() if granted -> Option DQuick Check:
Permission first, then token, then send [OK]
- Getting token before permission
- Sending notifications without token
- Skipping permission check
- Assuming permission is granted by default
Ready to prove it?
Pass the test and this pattern moves unknown
