Effortless Local Push Notifications in React Native with Expo

React Native|NOVEMBER 6, 2024|85 VIEWS
A Comprehensive Guide to Implementing Push Notifications in Your React Native Expo App

Introduction

In this guide, we will walk you through the process of setting up local push notifications in a React Native app using Expo. Push notifications are a crucial feature for engaging users and keeping them informed about important updates. With Expo, implementing push notifications becomes straightforward and efficient.

Difference Between Local and Remote Push Notifications

Local push notifications are notifications that are scheduled and triggered by the app itself on the user's device. They do not require a server to send the notification. These are useful for reminders, alarms, or any other type of notification that is based on time or user actions within the app.

Remote push notifications, on the other hand, are sent from a server to the user's device via a push notification service (such as Firebase Cloud Messaging or Apple's Push Notification Service). These are typically used for updates, messages, or any other type of notification that needs to be sent from an external source.

Step 1: Install Expo Notifications

To get started with local push notifications in your React Native app using Expo, you need to install the expo-notifications package. You can do this by running the following command in your project directory:

npx expo install expo-notifications

Step 2: Initialize the Notification Handler

First, set the handler that will cause the notification to show the alert

import * as Notifications from "expo-notifications";

Notifications.setNotificationHandler({
  handleNotification: async () => ({
    shouldShowAlert: true,
    shouldPlaySound: true,
    shouldSetBadge: false,
  }),
});

This can be done in your entry point file like App.js or _layout.tsx in a separate file, or you can even use Context API.

Expo notifications work by creating a notification that is assigned a unique ID. This ID can be used later to manage the notification, such as deleting it.

Step 3: Request Permission for Notifications

const checkAndRequestNotificationPermission = async () => {
  const { status: existingStatus } = await Notifications.getPermissionsAsync();
  let finalStatus = existingStatus;
  if (existingStatus !== "granted") {
    const { status } = await Notifications.requestPermissionsAsync();
    finalStatus = status;
  }
  if (finalStatus !== "granted") {
    return;
  }
};

useEffect(() => {
  checkAndRequestNotificationPermission();
}, []);

Step 4: Schedule Local Notification

In this example, we will trigger a notification at a specific time.

The function returns the ID of the scheduled notification.

const schedulePushNotification = async ({
    title,
    body,
    date,
  }: {
    title: string;
    body: string;
    date: Date;
  }) {
    const id = await Notifications.scheduleNotificationAsync({
      content: {
        title,
        body,
      },
      trigger: {
        date,
      },
    });
    return id;
  }

Step 5: Usage

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

Notifications.setNotificationHandler({
  handleNotification: async () => ({
    shouldShowAlert: true,
    shouldPlaySound: true,
    shouldSetBadge: false,
  }),
});

const App = () => {
  const checkAndRequestNotificationPermission = async () => {
    const { status: existingStatus } =
      await Notifications.getPermissionsAsync();
    let finalStatus = existingStatus;
    if (existingStatus !== "granted") {
      const { status } = await Notifications.requestPermissionsAsync();
      finalStatus = status;
    }
    if (finalStatus !== "granted") {
      return;
    }
  };

  const schedulePushNotification = async ({
    title,
    body,
    date,
  }: {
    title: string;
    body: string;
    date: Date;
  }) {
    const id = await Notifications.scheduleNotificationAsync({
      content: {
        title,
        body,
      },
      trigger: {
        date,
      },
    });
    return id;
  }

  useEffect(() => {
    checkAndRequestNotificationPermission();
  }, []);

  const handleScheduleNotification = async () => {
    const notificationId = await schedulePushNotification({
      title: "Reminder",
      body: "This is your scheduled notification",
      date: new Date(Date.now() + 60 * 1000), // Schedule to trigger in 1 minute
    });
    console.log("Notification scheduled with ID:", notificationId);
  };

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

export default App;

Step 6: Cancelling Notifications

You can use the ID above to cancel the local push notification.

const cancelNotification = async (notificationId: string) => {
  await Notifications.cancelScheduledNotificationAsync(notificationId);
};

Steps to Test

To test the local push notifications, you can follow these steps:

Run your app on a physical device: Push notifications do not work on iOS simulators, so you need to run your app on a physical device. For Android, you can use either a physical device or an emulator.

Schedule a notification: Use the "Schedule Notification" button in your app to schedule a notification. This will trigger a notification to be shown after the specified time (e.g., 1 minute).

Check the notification: After the specified time has passed, you should see the notification appear on your device. Make sure the notification displays the correct title and body.

Cancel a notification: If you want to test the cancellation of a notification, you can call the cancelNotification function with the ID of the scheduled notification before it triggers. Verify that the notification does not appear.

Test different scenarios: Test your notifications under different scenarios, such as when the app is in the foreground, background, or closed. Ensure that the notifications behave as expected in each case.

By following these steps, you can ensure that your local push notifications are working correctly in your React Native Expo app.

Conclusion

With these steps, you should be able to integrate local push notifications into your React Native Expo app effortlessly. Remember to test your notifications thoroughly to ensure they work as expected across different devices and scenarios.

Happy coding!