Edupala

Comprehensive Full Stack Development Tutorial: Learn Ionic, Angular, React, React Native, and Node.js with JavaScript

React Native Local Notifications Using Expo: A Tutorial

React Native is a popular framework for building cross-platform mobile applications using JavaScript and React. One of the features that React Native provides is the ability to send local notifications to users. In this tutorial, we will learn how to use React Native local notification using expo.

Here is the screenshot of React native local notification example when apps is closed.

React Native Local Notifications Using Expo

Introduction of React native local notification

Local notifications are a powerful way to interact with users by sending them reminders, alerts, or other information, even when they are not actively using your app. In this tutorial, we’ll explore how to implement local notifications in a React Native app using expo.

When to Use Local Notifications


React Native local notifications are a versatile tool for engaging with users by delivering messages directly on their device, even when the app is not in the foreground. However, their functionality when the app is completely closed (“killed” state) varies between platforms and specific use cases. Here’s when to use them and considerations for notifying users based on asynchronous API calls:

  1. Reminders/To-dos: Alert users about upcoming tasks, deadlines, or events.
  2. Location-based Alerts: Inform users about nearby points of interest.
  3. Progress Updates: Notify users about background task status (e.g., downloads, uploads).
  4. Promotions/Offers: Share limited-time deals or discounts based on user preferences.
  5. Content Updates: Update users about new, relevant content.

Limitations and Strategies for Local Notifications in Closed Apps:

  1. Background Fetch Limitations:
    • Available on both iOS and Android.
    • Allows execution of tasks at set intervals.
    • iOS has strict restrictions regarding time and frequency, impacting reliability for timely notifications.
  2. Push Notifications for Real-time Updates:
    • More effective for real-time or timely notifications based on server-side events.
    • Can reach users regardless of the app’s state (foreground, background, or closed).
  3. Scheduled Notifications Based on Last Data:
    • Involve scheduling local notifications based on the last fetched data before the app closes.
    • Useful for reminders or prompts based on available information, though not real-time.

React native local notifications example using Expo notifications

The first step is to install the Expo Notifications package. This package provides an API for sending local notifications in a React Native application. To install the package, run the following command in your project directory:

expo install expo-notifications

Create custom local notification component

To create local notification we need to import import * as Notifications from 'expo-notifications'; We can show notification based on different action like onPress or setInterval.

Set up a notification channel (Android only)
if you’re targeting Android, you’ll need to set up a notification channel before you can send notifications. A notification channel is a category of notifications that the user can customize. To set up a notification channel, call the setNotificationChannelAsync method and pass in an object with the channel’s properties.

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

Request permissions
Before you can send notifications, you need to request permission from the user. To request permissions, call the requestPermissionsAsync method. This method returns an object with the permission status.

const { status } = await Notifications.requestPermissionsAsync();
if (status !== 'granted') {
  Alert.alert('Notification permissions not granted!');
  return;
}

Adding listener for incoming notifications when apps on foreground

To add a listener for incoming notifications. This listener will be called whenever a notification is received while the app is running in the foreground. To add a listener, call the addNotificationReceivedListener method and pass in a callback function.

Notifications.addNotificationReceivedListener(handleNotification);

Where handlenNotification is callback function for incoming notifications.

Schedule a notification
We can also add schedule notification. We can schedule a notification to be sent at a later time. To schedule a notification, call the scheduleNotificationAsync method and pass in an object with the notification’s properties. For example, you can schedule a notification to be sent 30 seconds from now.

Notifications.scheduleNotificationAsync({
  content: {
    title: 'Tashi Delek',
    body: 'This is a local notification!',
  },
  trigger: { seconds: 30 },
});

Complete code of React native local notification using expo


import React, { useEffect, useRef } from "react";
import { View, Button, Platform, Alert } from "react-native";
import * as Notifications from "expo-notifications";

const LocalNotification = () => {
  const notificationListenerRef = useRef(null);
  useEffect(() => {
    registerForPushNotificationsAsync();

    // Cleanup function to remove the listener when the component unmounts
    return () => {
      if (notificationListenerRef.current) {
        Notifications.removeNotificationSubscription(notificationListenerRef.current);
      }
    };
  }, []);

  const registerForPushNotificationsAsync = async () => {
    if (Platform.OS === "android") {
      await Notifications.setNotificationChannelAsync("default", {
        name: "Local Notification Test",
        importance: Notifications.AndroidImportance.MAX,
        vibrationPattern: [0, 250, 250, 250],
        lightColor: "#FF231F7C",
      });
    } else {
      // Request notification permissions for iOS
      const { status } = await Notifications.requestPermissionsAsync({
        ios: {
          alert: true, // Request alert permissions
          badge: true, // Request badge permissions
          sound: true, // Request sound permissions
        },
      });
      if (status !== "granted") {
        Alert.alert("Notification permissions not granted!");
        return;
      }
    }

    notificationListenerRef.current = Notifications.addNotificationReceivedListener(
      handleNotification
    );
  };

  const handleNotification = (notification) => {
    Alert.alert(
      "Notification received!",
      notification?.request.content.body || notification.data?.body
    ); // Handle notification content based on platform
    console.log(notification);
  };

  const sendNotification = () => {
    Notifications.scheduleNotificationAsync({
      content: {
        title: "Tashi Delek",
        body: "This is a local notification!",
        data: { data: 'Data here Edupala' },
      },
      trigger: { seconds: 10 },
    });
  };

  return (
    <View style={{ flex: 1, justifyContent: "center", alignItems: "center" }}>
      <Button title="Send Notification" onPress={sendNotification} />
    </View>
  );
};

export default LocalNotification;

No Explicit Permission Request: Android doesn’t require explicit permission requests for local notifications. The channel setup implicitly grants the app the necessary permissions to display them.

React Native Local Notifications Using Expo: A Tutorial

Leave a Reply

Your email address will not be published. Required fields are marked *

Scroll to top