Learn Expo · 5/11

Working with Assets and Media

8 min read

Building a mobile application is about more than just rendering blank rectangular views and plain text. Users expect visually rich experiences: crisp images, perfectly legible custom typography, interactive audio, and seamless loading states.

However, handling media in native mobile development traditionally feels like negotiating a peace treaty between two fundamentally different alien species (iOS and Android). Fortunately, Expo abstracts the heavy lifting away.

Let's break down how to professionally manage assets and media in your React Native app, progressing step-by-step from static images to controlling the app's launch experience.


1. Managing Static Images and Expo Vector Icons 🖼️

Definition:
Static images are local visual files (like PNGs, JPGs, or WebPs) packaged directly with your app or fetched from a remote server. Vector icons are scalable, resolution-independent graphics drawn using mathematical coordinates rather than a fixed grid of pixels.

The Problem:
Mobile devices come in hundreds of different screen sizes and pixel densities. A standard static image might look perfectly crisp on an older phone but wildly pixelated on a modern ultra-HD screen. Furthermore, repeatedly downloading high-resolution images or keeping unoptimized images in memory will quickly drain the user's battery and cause the app to crash due to memory exhaustion.

The Solution:
Use expo-image for high-performance image caching, and @expo/vector-icons for lightweight, infinitely scalable iconography.

Under the Hood:
When you use the default React Native <Image> component, it does a decent job, but it lacks advanced caching. expo-image utilizes powerful native libraries (SDWebImage on iOS and Glide on Android). These libraries automatically cache your images both in the device's RAM (memory) and on the hard drive (disk). This prevents the UI from flickering when images reload and saves network bandwidth.

Installation

bash
npx expo install expo-image @expo/vector-icons

Hands-on Practice

In industry standards, it is common to use "BlurHash" strings as placeholders. A BlurHash is a tiny string of characters that represents a blurred version of your image. It loads instantly while the real image fetches in the background.

tsx
import { View, StyleSheet } from 'react-native';
import { Image } from 'expo-image';
import FontAwesome from '@expo/vector-icons/FontAwesome';

export default function ProfileScreen() {
  return (
    <View style={styles.container}>
      {/* 
        Using expo-image. We provide a blurhash placeholder 
        for a smooth, flicker-free loading experience.
      */}
      <Image
        style={styles.image}
        source={{ uri: 'https://example.com/high-res-profile.jpg' }}
        placeholder="L6PZfSi_.AyE_3t7t7R**0o#DgR4"
        contentFit="cover"
        transition={1000} // Fades in beautifully over 1 second
      />
      
      {/* Using an Expo Vector Icon - sharp on every device */}
      <FontAwesome name="user-circle" size={32} color="#1E1E1E" />
    </View>
  );
}

const styles = StyleSheet.create({
  container: { flex: 1, alignItems: 'center', justifyContent: 'center', gap: 20 },
  image: { width: 150, height: 150, borderRadius: 75 },
});

2. Custom Fonts: Loading and Managing Typography 🔤

Definition:
Custom fonts are .ttf or .otf files that dictate the exact textual style of your application, overriding the default system fonts (like San Francisco on iOS or Roboto on Android).

The Problem:
An app using default system fonts often lacks brand identity. However, custom fonts are heavy files. If React Native tries to render a <Text> component using a custom font before that font file is fully loaded into the device's memory, the app will either throw a fatal error or fall back to a system font. If it falls back, the text will suddenly "pop" into the custom font a few seconds later, which looks incredibly unprofessional.

The Solution:
Use expo-font to load typography asynchronously during the app's initialization phase. You intentionally block the UI from rendering the text until the font is strictly confirmed as loaded.

The System Flow:
Imagine you are organizing a theater play. The actors (your text) are standing on stage, but their costumes (the fonts) are still in the delivery truck. If you open the curtains now, the audience sees actors in sweatpants. Instead, you keep the curtains closed until the costumes arrive. Once everyone is dressed, you open the curtains for a flawless presentation.

Installation

bash
npx expo install expo-font

Hands-on Practice

tsx
import { Text, View, ActivityIndicator } from 'react-native';
import { useFonts } from 'expo-font';

export default function TypographyScreen() {
  // Load local font files asynchronously
  const [fontsLoaded] = useFonts({
    'BrandFont-Bold': require('./assets/fonts/BrandFont-Bold.ttf'),
  });

  // Keep the "curtains closed" until fonts are ready
  // In a real app, you would keep the splash screen visible here
  if (!fontsLoaded) {
    return (
      <View style={{ flex: 1, justifyContent: 'center' }}>
        <ActivityIndicator size="large" />
      </View>
    );
  }

  return (
    <View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}>
      <Text style={{ fontFamily: 'BrandFont-Bold', fontSize: 24 }}>
        This is our custom branded text!
      </Text>
    </View>
  );
}

3. Audio and Video Playback with Expo AV 🎵

Definition:
expo-av is a universal module providing programmatic interfaces (APIs) and UI components to play, record, and control the state of audio and video files.

The Problem:
Playing media requires tapping directly into the operating system's native media players. Managing playback states (buffering, pausing, seeking) across different operating systems is tedious. More importantly, if you play an audio file and the user navigates away from the screen without properly destroying the audio instance, the music will awkwardly keep playing in the background, permanently hogging device memory.

The Solution:
expo-av wraps the complex native implementations into a unified JavaScript API, making it easy to track playback state and safely unload media from memory when components unmount.

💡 Interesting Industry Fact: Technology moves fast! As of Expo SDK 52, the Expo team has officially deprecated expo-av in favor of two modular, highly optimized libraries: expo-video and expo-audio. expo-av is slated for complete removal in SDK 55. However, because thousands of massive production codebases currently rely heavily on expo-av, maintaining and understanding this library remains a critical industry skill.

Installation

bash
npx expo install expo-av

Hands-on Practice

When dealing with audio, memory management is your biggest responsibility. You must unload the sound.

tsx
import { useEffect, useState } from 'react';
import { View, Button, StyleSheet } from 'react-native';
import { Audio } from 'expo-av';

export default function AudioPlayer() {
  const [sound, setSound] = useState<Audio.Sound | null>(null);

  async function playSound() {
    console.log('Loading Sound');
    // Instantiate and load the sound object
    const { sound: newSound } = await Audio.Sound.createAsync(
      require('./assets/sounds/notification.mp3')
    );
    
    setSound(newSound);
    
    console.log('Playing Sound');
    await newSound.playAsync();
  }

  // Cleanup: Under the hood, audio instances consume native device memory. 
  // We explicitly unload them when the component unmounts.
  useEffect(() => {
    return sound
      ? () => {
          console.log('Unloading Sound');
          sound.unloadAsync();
        }
      : undefined;
  }, [sound]);

  return (
    <View style={styles.container}>
      <Button title="Play Notification" onPress={playSound} />
    </View>
  );
}

const styles = StyleSheet.create({
  container: { flex: 1, justifyContent: 'center', alignItems: 'center' }
});

4. Configuring Splash Screens and App Icons (app.json) 🚀

Definition:
The app icon is the static image representing your application on the user's home screen. The splash screen (launch screen) is the initial holding view displayed by the operating system while the app's JavaScript bundle parses and loads into memory.

The Problem:
When an app launches, there is a physical delay between the user tapping the app icon and the React Native engine successfully mounting your UI. If you do not configure a splash screen, users will stare at a blank white screen, making your app feel broken, sluggish, or unresponsive. Furthermore, Android and iOS have strict, vastly different requirements for icon geometry (e.g., Android's Adaptive Icons require separate foreground and background layers).

The Solution:
Define your graphical assets centrally in app.json. Use the expo-splash-screen package to intercept the system's loading behavior, forcing the splash screen to stay visible until your assets (like custom fonts or initial API calls) are 100% ready.

The System Flow:
Imagine running a fancy restaurant. The app icon is the glowing sign outside that brings customers in. The splash screen is your waiting area. If you don't have a waiting area, customers walk straight into an unorganized dining room where waiters are still frantically setting tables. expo-splash-screen acts as the host, politely holding customers in the lobby until their specific table (your UI) is perfectly prepared.

Installation

bash
npx expo install expo-splash-screen

Hands-on Practice: Configuration

First, define how the assets look in your app.json file. Expo takes these definitions and automatically generates all the required native sizes during the build process.

json
{
  "expo": {
    "name": "PizzaShopApp",
    "icon": "./assets/icon.png",
    "splash": {
      "image": "./assets/splash-icon.png",
      "resizeMode": "contain",
      "backgroundColor": "#FF5733"
    },
    "android": {
      "adaptiveIcon": {
        "foregroundImage": "./assets/adaptive-icon.png",
        "backgroundColor": "#FF5733"
      }
    }
  }
}

Hands-on Practice: Controlling the Display Lifecycle

In your main App.tsx or Root Layout, you tell the splash screen to wait.

tsx
import { useEffect, useState, useCallback } from 'react';
import { View, Text, StyleSheet } from 'react-native';
import * as SplashScreen from 'expo-splash-screen';
import * as Font from 'expo-font';
import Entypo from '@expo/vector-icons/Entypo';

// 1. Tell the system to NOT hide the splash screen automatically
SplashScreen.preventAutoHideAsync();

// 2. Optional: Configure a smooth fade out (Supported in modern Expo SDKs)
SplashScreen.setOptions({
  duration: 800,
  fade: true,
});

export default function App() {
  const [appIsReady, setAppIsReady] = useState(false);

  useEffect(() => {
    async function prepare() {
      try {
        // Pre-load necessary assets (fonts, icons, database connections)
        await Font.loadAsync(Entypo.font);
        
        // Simulate an API call delay for demonstration
        await new Promise(resolve => setTimeout(resolve, 2000));
      } catch (e) {
        console.warn(e);
      } finally {
        // Assets are loaded!
        setAppIsReady(true);
      }
    }

    prepare();
  }, []);

  const onLayoutRootView = useCallback(async () => {
    if (appIsReady) {
      // 3. Hide the splash screen ONLY once the root view has safely rendered
      await SplashScreen.hideAsync();
    }
  }, [appIsReady]);

  if (!appIsReady) {
    return null; // Keep rendering nothing while splash screen shows
  }

  return (
    <View style={styles.container} onLayout={onLayoutRootView}>
      <Text style={styles.text}>App is perfectly ready!</Text>
      <Entypo name="rocket" size={40} color="#FF5733" />
    </View>
  );
}

const styles = StyleSheet.create({
  container: { flex: 1, alignItems: 'center', justifyContent: 'center', gap: 10 },
  text: { fontSize: 20, fontWeight: 'bold' }
});

Further Reading & Official Documentation

Challenge

Professional App Loading and Asset Management in Expo

You are tasked with building a React Native component that demonstrates a professional application startup sequence and handles various asset types using the Expo SDK. Your goal is to integrate font loading, splash screen control, high-performance image display, vector icons, and audio playback with proper memory management.

Requirements:

  1. Splash Screen Control: On component mount, immediately prevent the native splash screen from auto-hiding. It should only be hidden after all essential assets are loaded.
  2. Asset Loading: Asynchronously load a custom font. The font is named Inter-Bold and is located at ./assets/fonts/Inter-Bold.ttf. You can assume this loading function is available.
  3. State Management: Use React hooks (useState, useEffect) to track whether the app's assets are ready.
  4. Conditional Rendering: The main application view should not be rendered until all assets are confirmed to be loaded. While loading, nothing should be displayed (the splash screen will be visible). Use the onLayout prop of your root View to safely hide the splash screen once the view is ready to be painted.
  5. UI Implementation: Once assets are ready, render a view that includes:
    • A Text component displaying "Welcome to the App!" styled with the custom Inter-Bold font.
    • An Image component from expo-image displaying a remote image. Use https://picsum.photos/seed/696/3000/2000 as the source and 'LKN]Rv%2My?bfQ_2_~ITx]t7-URj' as the blurhash placeholder.
    • An AntDesign icon with the name star and size 24 from @expo/vector-icons.
    • A Button with the title "Play Sound".
  6. Audio Handling:
    • When the "Play Sound" button is pressed, play an audio file located at ./assets/audio/sound.mp3. You can assume an Audio.Sound object is used for this.
    • Crucially, ensure the audio resource is properly created on component mount and fully unloaded and released from memory when the component unmounts to prevent memory leaks.

Expected result

Your final code should correctly implement a complete app loading sequence within a single React component.

  1. The useEffect hook should be the central point for orchestration.
    • It must call SplashScreen.preventAutoHideAsync() at the beginning.
    • It must call Font.loadAsync({'Inter-Bold': require(...)}).
    • It should create and load an Audio.Sound object, then store it in state using setSound.
    • The finally block must call setAppIsReady(true).
    • It must return a cleanup function that checks if the sound object exists and calls sound.unloadAsync().
  2. A memoized function, onLayoutRootView, created with useCallback should check if (appIsReady) before calling SplashScreen.hideAsync().
  3. The root View in the returned JSX must have its onLayout prop set to onLayoutRootView.
  4. The JSX rendered when appIsReady is true should contain:
    • <Text style={{ fontFamily: 'Inter-Bold', fontSize: 24 }}>Welcome to the App!</Text>
    • <Image source="..." blurhash="..." ... /> from expo-image.
    • <AntDesign name="star" size={24} color="black" />.
    • <Button title="Play Sound" onPress={playSound} />.
  5. The playSound function should use the sound object from state and call sound.replayAsync() or sound.playAsync() to play the audio.
jsx

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.