Learn Expo · 10/11

Advanced Features and Native Integration

10 min read

As your application matures, you will eventually outgrow the basic components and step into the realm of native integrations and performance tuning. Managing native code, handling system-level push notifications, writing custom native bridges, and profiling performance are the hallmarks of a production-grade application.

This guide covers the advanced, industry-standard practices used to scale and maintain complex Expo applications.


1. Continuous Native Generation (CNG) and Prebuilds

Definition

Continuous Native Generation (CNG) is the process of dynamically generating your app's native iOS and Android project directories (/ios and /android) on-demand from a centralized configuration file, rather than keeping them permanently in your source control.

The Problem

Historically, building a React Native app meant you generated the ios and android folders once at the start of the project. From that day forward, those folders became your responsibility. If you needed to upgrade your React Native version, add a new permission, or install a complex native dependency, you had to manually edit native files like AndroidManifest.xml or AppDelegate.mm.

Over time, these folders become a messy graveyard of patches and manual tweaks. Upgrading React Native became a dreaded task, often leading to broken builds and wasted weeks.

The Solution: CNG and Prebuild

CNG solves this by treating your native folders as disposable build artifacts. Instead of manually editing native code to configure your app, you declare your configuration in your app.json (or app.config.js).

When you run the npx expo prebuild command, Expo takes your clean JavaScript project, reads your configuration, and stamps out brand new, perfectly configured ios and android folders.

Imagine you are a franchise restaurant owner. Instead of manually building every new restaurant brick-by-brick and hoping the plumbing connects (manual native code management), you create a standardized master blueprint (app.json). Whenever you need a new building, a highly efficient factory instantly drops a fully functioning restaurant onto the lot (npx expo prebuild). If you want to change the color of the walls, you update the blueprint, bulldoze the old restaurant, and drop a new one in seconds.

Industry Standard Workflow

In modern Expo development, you should almost never commit your native folders to Git.

  1. Add /ios and /android to your .gitignore.
  2. Configure your app heavily inside app.json.
  3. Use Config Plugins (libraries that automatically inject native code during prebuild) for third-party libraries.
  4. Run npx expo prebuild --clean whenever you add a new native dependency. Deleting your ios and android folders used to be a developer's worst nightmare. Now, it's just a therapeutic Tuesday afternoon.

2. Push Notifications: Setup, Tokens, and Listeners

Definition

Push notifications are system-level alerts sent from a remote server to a user's device, capable of waking up the device and displaying a message even when the application is completely closed.

The Problem

Setting up remote notifications directly with Apple Push Notification service (APNs) and Firebase Cloud Messaging (FCM) is tedious. You have to handle two completely different architectures, manage multiple security certificates, parse different token formats, and write distinct code to handle incoming data on both iOS and Android.

The Solution: Expo Push Service

Expo provides a unified service and SDK (expo-notifications) that abstracts away the differences between Apple and Google. You request a single "Expo Push Token" from the device. You save this token in your database. When you want to send a notification, your backend sends a request to Expo's servers, and Expo securely routes it to the correct platform (APNs or FCM).

Think of Expo Push Service as an international post office. People (users) register their home address with you. Instead of you figuring out the specific mail routing protocols for 195 different countries, you just hand your letters to the Expo postmaster with a universal ID (the Expo Push Token). The postmaster handles the complex border crossings and delivers the message to Apple or Google.

Step-by-Step Setup

1. Installation
Always fetch the latest package to ensure compatibility:

bash
npx expo install expo-notifications expo-device expo-constants

2. Getting the Push Token
You need to ask the user for permission and then fetch the token. This token is what your backend will use to target this specific device.

javascript
import * as Notifications from 'expo-notifications';
import * as Device from 'expo-device';
import Constants from 'expo-constants';
import { Platform } from 'react-native';

// Set up how notifications should appear when the app is in the foreground
Notifications.setNotificationHandler({
  handleNotification: async () => ({
    shouldShowAlert: true,
    shouldPlaySound: true,
    shouldSetBadge: false,
  }),
});

export async function registerForPushNotificationsAsync() {
  let token;

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

  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;
    }
    
    // projectId is required for Expo Go and EAS Build environments
    const projectId = Constants.expoConfig?.extra?.eas?.projectId;
    token = (await Notifications.getExpoPushTokenAsync({ projectId })).data;
    
    console.log("Your Expo Push Token:", token);
  } else {
    alert('Must use physical device for Push Notifications');
  }

  return token;
}

3. Listening to Notifications
You need to know when a notification arrives while the app is open, or when a user taps on one.

javascript
import { useEffect, useRef } from 'react';

export default function App() {
  const notificationListener = useRef();
  const responseListener = useRef();

  useEffect(() => {
    // Fired whenever a notification is received while the app is foregrounded
    notificationListener.current = Notifications.addNotificationReceivedListener(notification => {
      console.log('Notification received:', notification);
    });

    // Fired whenever a user taps on or interacts with a notification
    responseListener.current = Notifications.addNotificationResponseReceivedListener(response => {
      console.log('User tapped notification:', response.notification.request.content.data);
    });

    return () => {
      Notifications.removeNotificationSubscription(notificationListener.current);
      Notifications.removeNotificationSubscription(responseListener.current);
    };
  }, []);

  return <YourAppUI />;
}

(Note: Starting from SDK 53, push notifications do not work on Android within the Expo Go app. You must build a custom development client using npx expo run:android or EAS Build).


3. Writing Custom Native Code: Introduction to Expo Modules API

Definition

The Expo Modules API is a framework that allows you to write custom native code (Swift for iOS, Kotlin for Android) and expose it directly to your JavaScript codebase.

The Problem

Sometimes, you need to use a specialized piece of hardware (like a custom Bluetooth terminal) or a proprietary native SDK that doesn't have a React Native library. In the past, writing "Native Modules" required deep knowledge of C++, Objective-C, and Java. You had to manually configure the React Native "Bridge," deal with asynchronous serialization, and write massive amounts of boilerplate just to say "Hello World" from native to JS.

The Solution: Expo Modules API

The Expo Modules API abstracts away the legacy Bridge and the underlying C++ JSI (JavaScript Interface). It provides a clean, domain-specific language (DSL) in Swift and Kotlin. You define functions normally in those languages, and Expo handles securely binding them to JavaScript. It is heavily optimized, type-safe, and compatible with React Native's New Architecture by default.

How it looks in practice

If you needed to create a custom module, you would initialize it using Expo's CLI:

bash
npx create-expo-module my-custom-module

Inside your Swift file (ios/MyCustomModule.swift):
The syntax is incredibly readable. You define a Module class and list your functions.

swift
import ExpoModulesCore

public class MyCustomModule: Module {
  public func definition() -> ModuleDefinition {
    // The name exported to JavaScript
    Name("MyCustomModule")

    // A synchronous function exposed to JS
    Function("helloWorld") { (name: String) -> String in
      return "Hello, \(name)! This is Swift 🍎"
    }

    // An asynchronous function (Returns a Promise in JS)
    AsyncFunction("fetchHeavyData") { (promise: Promise) in
      // Do some heavy native work...
      promise.resolve("Data fetched successfully")
    }
  }
}

Inside your JavaScript file:
You can call these native methods as if they were standard JavaScript functions.

javascript
import { helloWorld, fetchHeavyData } from 'my-custom-module';

// Executes Swift/Kotlin synchronously 
const greeting = helloWorld('Developer');
console.log(greeting); // "Hello, Developer! This is Swift 🍎"

// Executes asynchronously
const data = await fetchHeavyData();

You get incredible native performance without touching a single line of C++ or Objective-C header files.


4. Performance Profiling and Identifying Bottlenecks

Definition

Performance profiling is the systematic process of analyzing your application to measure memory usage, CPU load, and rendering speed to identify specific areas (bottlenecks) that cause lag or crashes.

The Problem

In React Native, your application primarily runs across two main threads:

  1. The Native UI Thread: Handles rendering the graphics to the screen.
  2. The JavaScript Thread: Runs your business logic, API calls, and React state.

If you make the JavaScript thread do too much heavy synchronous work (like parsing a massive JSON file or running a deeply nested for loop), it gets blocked. When the JS thread is blocked, it cannot communicate with the Native UI thread, causing animations to stutter, buttons to become unresponsive, and the app to feel "frozen."

Imagine a restaurant kitchen. The JavaScript Thread is the Head Chef, and the Native UI thread is the Wait Staff. The Wait Staff needs constant instructions from the Head Chef on where to take the food. If you force the Head Chef to personally chop 10,000 onions in the corner (heavy synchronous computation), they can't talk to the Wait Staff. The Wait Staff stands around doing nothing, the food gets cold, and the customers (users) get angry. You need to profile the kitchen to realize the onion-chopping is the bottleneck.

The Solution: Profiling Tools and Best Practices

Expo provides built-in integrations to see exactly what your app is doing under the hood.

1. Chrome DevTools & Hermes

The default JavaScript engine in Expo is Hermes. It is highly optimized for mobile. To profile JS performance:

  • Start your app using npx expo start.
  • Press j in the terminal to open Chrome DevTools connected directly to the Hermes engine.
  • Go to the Performance tab and click Record. This will generate a flame chart showing exactly which JavaScript functions are taking the longest to execute.

2. React DevTools

Sometimes the app is slow not because of heavy computation, but because components are re-rendering excessively.

  • Press Shift + m in the Expo terminal to toggle the developer menu, or use the DevTools plugin.
  • Open the React Profiler.
  • Enable "Highlight updates when components render".
  • Interact with your app. If the whole screen flashes green every time you type a single letter into a text input, you have a massive re-render bottleneck.

3. Industry Fixes for Common Bottlenecks

  • List Rendering: Never use ScrollView for long lists of data. Always use FlatList, or better yet, use Shopify's @shopify/flash-list which reuses views natively and prevents memory leaks.
  • Heavy Animations: Do not animate layouts using React State (useState). Use react-native-reanimated. Reanimated moves the animation calculations entirely over to the Native UI thread (using Web Worker-like constructs called "Worklets"), so even if your JS thread is completely blocked chopping onions, your animations will remain buttery smooth at 60 frames per second.
  • Image Optimization: Unoptimized images are the #1 cause of app crashes due to memory limits. Use expo-image instead of the standard Image component. It aggressively caches images and utilizes native memory management to keep your app fast.

Additional Resources

To dive deeper into these concepts, reference the official documentation:

Challenge

You are building a production-grade Expo application and need to implement a robust push notification setup.

Your task is to complete the PushNotificationManager component. Implement the logic within a useEffect hook to perform the following actions when the component mounts:

  1. Define an asynchronous function named registerForPushNotificationsAsync.
  2. Inside this function, first, check the device's current notification permissions using Notifications.getPermissionsAsync().
  3. If permissions are not granted (status !== 'granted'), request them using Notifications.requestPermissionsAsync(). If the user still denies permission, use an Alert to inform them that they need to enable permissions to receive notifications and then exit the function.
  4. If permissions are granted, retrieve the unique Expo Push Token. You'll need to specify the projectId for getExpoPushTokenAsync as it's a required parameter. For this challenge, use the placeholder string 'your-expo-project-id'. Store the retrieved token's data in the expoPushToken state.
  5. On Android, you must set a notification channel. Perform a platform check, and if Platform.OS is 'android', call Notifications.setNotificationChannelAsync. Use 'default' as the channel ID, give it a name of 'default', and set the importance to Notifications.AndroidImportance.MAX.
  6. Back in the useEffect hook, after defining your async function, call it. Then, set up two notification listeners:
    • One using addNotificationReceivedListener to update the notification state when a notification is received while the app is in the foreground. Store the subscription in notificationListener.current.
    • One using addNotificationResponseReceivedListener. For this challenge, the callback can simply log the response. Store the subscription in responseListener.current.
  7. Finally, return a cleanup function from useEffect that removes both listeners using Notifications.removeNotificationSubscription to prevent memory leaks.

Expected result

The solution should contain a useEffect hook that performs the following:

  1. It defines an inner asynchronous function, registerForPushNotificationsAsync.
  2. Inside this function, it correctly checks for notification permissions using await Notifications.getPermissionsAsync().
  3. If permissions are not granted, it calls await Notifications.requestPermissionsAsync() to ask the user.
  4. It handles the case where permission is still denied by showing an Alert and returning early from the function.
  5. It correctly calls await Notifications.getExpoPushTokenAsync({ projectId: 'your-expo-project-id' }) and updates the expoPushToken state with the data property of the result.
  6. It includes a platform check (Platform.OS === 'android') and, if true, calls await Notifications.setNotificationChannelAsync with appropriate parameters (id, name, importance).
  7. The useEffect hook calls registerForPushNotificationsAsync().
  8. It subscribes to notifications using Notifications.addNotificationReceivedListener and Notifications.addNotificationResponseReceivedListener, storing the subscription objects in the notificationListener.current and responseListener.current refs.
  9. The addNotificationReceivedListener callback correctly updates the notification state using setNotification.
  10. It returns a cleanup function from useEffect that calls Notifications.removeNotificationSubscription for both listeners using the stored refs to prevent memory leaks.
javascript

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.