0
0
React Nativemobile~15 mins

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

Choose your learning style9 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.