Bird
Raised Fist0
React Nativemobile~15 mins

Push notifications (expo-notifications) in React Native - Deep Dive

Choose your learning style10 modes available
Overview - Push notifications (expo-notifications)
What is it?
Push notifications are messages sent by an app to a user's device even when the app is not open. Expo-notifications is a library that helps React Native apps send and receive these messages easily. It manages permissions, device tokens, and handles incoming notifications. This lets apps alert users about important updates or events instantly.
Why it matters
Without push notifications, apps would have to rely on users opening them to see updates, which can reduce engagement and timely responses. Push notifications keep users connected and informed, improving user experience and retention. They solve the problem of reaching users in real-time, even if the app is closed or in the background.
Where it fits
Before learning push notifications, you should understand React Native basics and how to use Expo for app development. After mastering push notifications, you can explore advanced topics like background tasks, notification channels, and integrating with backend services for personalized messaging.
Mental Model
Core Idea
Push notifications are like instant messages from your app that pop up on your device to grab your attention, managed by expo-notifications to simplify sending and receiving.
Think of it like...
Imagine your phone is like a mailbox. Normally, you have to open the mailbox (app) to check for mail (updates). Push notifications are like a mail carrier who rings your doorbell to tell you there’s new mail waiting, so you don’t have to check constantly.
┌─────────────────────────────┐
│       App Server            │
│  (sends notification)       │
└─────────────┬───────────────┘
              │
              ▼
┌─────────────────────────────┐
│  Expo Notification Service  │
│  (routes & manages tokens)  │
└─────────────┬───────────────┘
              │
              ▼
┌─────────────────────────────┐
│      User Device            │
│  (receives & displays       │
│   push notification)        │
└─────────────────────────────┘
Build-Up - 7 Steps
1
FoundationWhat Are Push Notifications
🤔
Concept: Introduce the basic idea of push notifications and their purpose.
Push notifications are short messages sent by apps to your phone or tablet. They appear even if you are not using the app. For example, a weather app might send a notification about a storm. This helps apps keep you informed without needing to open them.
Result
You understand that push notifications are alerts from apps that appear on your device anytime.
Knowing what push notifications are helps you see why apps use them to stay connected with users.
2
FoundationExpo-Notifications Library Basics
🤔
Concept: Learn what expo-notifications is and how it helps with push notifications in React Native.
Expo-notifications is a tool that makes it easy to add push notifications to your React Native app. It handles asking the user for permission, getting a unique device token, and listening for notifications. This saves you from writing complex code for each platform.
Result
You can set up basic notification handling in your app with simple commands.
Understanding expo-notifications simplifies the complex process of managing push notifications across devices.
3
IntermediateRequesting Permissions and Getting Tokens
🤔Before reading on: do you think the app can send notifications without asking the user first? Commit to yes or no.
Concept: Learn how to ask users for permission and get a device token to send notifications.
To send push notifications, your app must ask the user for permission. Expo-notifications provides a method to request this. Once granted, the app gets a unique token identifying the device. This token is sent to your server to target notifications to that device.
Result
Your app can now ask permission and obtain a token needed to send notifications.
Knowing that permission and tokens are required prevents errors and respects user privacy.
4
IntermediateHandling Incoming Notifications
🤔Before reading on: do you think notifications only appear when the app is open? Commit to yes or no.
Concept: Learn how to listen for and respond to notifications when the app is foregrounded or backgrounded.
Expo-notifications lets your app listen for notifications while it is running. You can show alerts, update UI, or navigate users based on notification content. Notifications can also appear when the app is closed, handled by the device system.
Result
Your app reacts to notifications in real-time, improving user experience.
Understanding notification handling lets you create interactive and responsive apps.
5
IntermediateSending Notifications from a Server
🤔Before reading on: do you think the app itself sends notifications or a server does? Commit to your answer.
Concept: Learn that notifications are usually sent from a backend server using the device token.
Your app sends the device token to a server you control. The server uses this token to send push notifications through Expo's push service. This allows sending messages based on events like new messages or reminders.
Result
You can trigger notifications remotely, not just locally on the device.
Knowing the server role clarifies how notifications reach users even when the app is closed.
6
AdvancedNotification Channels and Customization
🤔Before reading on: do you think all notifications look and behave the same on Android? Commit to yes or no.
Concept: Learn about notification channels on Android and how to customize notification appearance and behavior.
Android uses notification channels to group notifications by importance and sound. Expo-notifications lets you create and customize these channels. You can set sounds, vibration, and priority to control how notifications alert users.
Result
Your notifications can be tailored to user preferences and platform standards.
Understanding channels helps you create respectful and effective notifications on Android.
7
ExpertHandling Edge Cases and Background Behavior
🤔Before reading on: do you think notifications always arrive instantly and reliably? Commit to yes or no.
Concept: Explore challenges like delayed delivery, permission changes, and background restrictions on different devices.
Push notifications depend on device settings, network, and OS policies. Sometimes notifications are delayed or blocked if permissions change or battery saver modes are active. Expo-notifications provides tools to check permissions and handle these cases gracefully.
Result
Your app can handle real-world issues, improving reliability and user trust.
Knowing these edge cases prepares you to build robust notification features that work well in production.
Under the Hood
When an app registers for push notifications, expo-notifications requests permission and obtains a unique device token from the platform's notification service (APNs for iOS, FCM for Android). This token is sent to your backend server. When the server wants to notify the user, it sends a message to Expo's push notification service, which forwards it to the platform's service using the token. The platform then delivers the notification to the device, which displays it or passes it to the app if running.
Why designed this way?
This layered design separates concerns: device tokens are managed by platform services for security and scalability, Expo provides a unified API to simplify cross-platform development, and backend servers control when and what notifications to send. Alternatives like direct platform integration are more complex and error-prone, so Expo abstracts this complexity for developers.
┌───────────────┐       ┌───────────────┐       ┌───────────────┐
│   User Device │◄──────│Platform Push  │◄──────│ Expo Push     │
│ (Expo Client) │       │ Notification  │       │ Notification  │
└───────┬───────┘       │ Service (APNs,│       │ Service       │
        │               │ FCM)          │       └───────┬───────┘
        │               └───────┬───────┘               │
        │                       │                       │
        │                       │                       │
        ▼                       ▼                       ▼
┌───────────────┐       ┌───────────────┐       ┌───────────────┐
│ React Native  │       │ Backend Server│       │ Developer App │
│ App (expo-    │──────▶│ (sends push   │──────▶│ (sends token) │
│ notifications)│       │ notifications)│       └───────────────┘
└───────────────┘       └───────────────┘
Myth Busters - 4 Common Misconceptions
Quick: Do you think push notifications can be sent without user permission? Commit yes or no.
Common Belief:Push notifications can be sent anytime without asking the user.
Tap to reveal reality
Reality:Apps must request and receive user permission before sending push notifications.
Why it matters:Ignoring permission leads to app rejection or users disabling notifications, reducing app effectiveness.
Quick: Do you think push notifications always arrive instantly and reliably? Commit yes or no.
Common Belief:Push notifications are guaranteed to arrive immediately on all devices.
Tap to reveal reality
Reality:Delivery can be delayed or blocked due to network issues, device settings, or OS restrictions.
Why it matters:Assuming instant delivery can cause poor user experience if notifications are missed or late.
Quick: Can you send push notifications directly from the app without a server? Commit yes or no.
Common Belief:The app itself sends push notifications directly to other devices.
Tap to reveal reality
Reality:Push notifications are sent from a backend server or cloud service, not directly from the app.
Why it matters:Trying to send notifications directly from the app is technically impossible and leads to confusion.
Quick: Do you think all notifications look the same on Android and iOS? Commit yes or no.
Common Belief:Notifications behave and appear identically on all platforms.
Tap to reveal reality
Reality:Android and iOS have different notification systems and customization options.
Why it matters:Ignoring platform differences can cause inconsistent user experiences and missed features.
Expert Zone
1
Expo-notifications abstracts platform differences but sometimes requires native code for advanced features like custom sounds or actions.
2
Device tokens can change over time; apps must handle token refresh to maintain notification delivery.
3
Background notification handling differs by OS version and device manufacturer, affecting reliability.
When NOT to use
Push notifications are not suitable for large data transfers or real-time chat; use WebSockets or other real-time protocols instead. Also, avoid overusing notifications to prevent user annoyance and opt for in-app messaging when possible.
Production Patterns
In production, developers use backend services to send personalized notifications triggered by user actions or schedules. They implement analytics to track notification effectiveness and use notification channels on Android to respect user preferences.
Connections
Web Push Notifications
Similar pattern
Understanding mobile push notifications helps grasp web push, as both use device tokens and permission models to deliver messages.
Event-Driven Architecture
Builds-on
Push notifications often rely on event-driven backend systems that trigger messages when specific events occur, linking app behavior to server events.
Postal Mail System
Analogy in logistics
Like postal mail, push notifications require addressing (device tokens), routing (Expo service), and delivery (platform services), showing how complex systems simplify user communication.
Common Pitfalls
#1Not requesting user permission before sending notifications.
Wrong approach:const token = await Notifications.getExpoPushTokenAsync(); // Sending notifications without asking permission first
Correct approach:const { status } = await Notifications.requestPermissionsAsync(); if (status === 'granted') { const token = await Notifications.getExpoPushTokenAsync(); }
Root cause:Assuming permission is automatic or unnecessary leads to errors and poor user experience.
#2Hardcoding device tokens and not handling token refresh.
Wrong approach:const token = 'fixed-token-string'; // Using this token forever without updates
Correct approach:const token = await Notifications.getExpoPushTokenAsync(); // Update token on server whenever it changes
Root cause:Not realizing tokens can change causes notification delivery failures.
#3Ignoring platform differences and using the same notification settings everywhere.
Wrong approach:Notifications.setNotificationChannelAsync('default', { importance: Notifications.AndroidImportance.DEFAULT }); // Using default channel without customization
Correct approach:Notifications.setNotificationChannelAsync('alerts', { name: 'Alerts', importance: Notifications.AndroidImportance.HIGH, sound: 'alert.wav' });
Root cause:Assuming all platforms behave the same leads to suboptimal notification behavior.
Key Takeaways
Push notifications let apps send timely messages to users even when apps are closed.
Expo-notifications simplifies cross-platform notification handling in React Native apps.
User permission and device tokens are essential for sending push notifications securely.
Notifications depend on backend servers to trigger messages using device tokens.
Handling platform differences and edge cases ensures reliable and user-friendly notifications.

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